I have a many-to-many relationship defined by a join model:
class Product < ActiveRecord::Base
has_many :bundles, :through => :bundlings
class Bundling < ActiveRecord::Base
class Bundle < ActiveRecord::Base
has_many :products, :through => :bundlings
Additionally, Bundle validates that it contains at least two products.
Then I tried to create a new Bundle like this:
bundle = Bundle.new(…) # can’t save bundle yet since
# I haven't yet added two products
bundle.products << products(:product_one)
bundle.products << products(:product_two)
The “<<” operation raises an**ActiveRecord:: HasManyThroughCantAssociateNewRecords exception, saying that both bundle and the product need to have an ID to use “<<” on a through association. However, in order to obtain an ID, I need to save bundle, but bundle cannot be saved (i.e. pass validation) unless I have added two products to it through “<<” – Catch 22.