bullet icon indicating copy to clipboard operation
bullet copied to clipboard

Creating record with many to many association triggers eager loading error

Open denmarkmeralpis opened this issue 4 years ago • 1 comments

Hi, I dunno if this is a valid bug but here's how I experienced it:

Models

# product.rb
belongs_to :another_model
has_many :product_categories
has_many :categories, through: :product_categories

# product_category.rb
belongs_to :category
belongs_to :product

# category.rb
belongs_to :another_model
has_many :product_categories
has_many :products, through: :product_categories

# another_model.rb
has_many :categories
has_many :products

when I tried this:

product = Product.new(category_ids: [1, 2, 3], name: 'Foo')
product.save

I got an error

USE eager loading detected Category => [:another_model] Add to your finder: :includes => [:another_model]

I dunno why I got that error. Can somebody help me? Thank you

denmarkmeralpis avatar Apr 15 '20 10:04 denmarkmeralpis

I resolved similar problem as follows.

categories = Category.includes(:another_model).find([1, 2, 3])
product = Product.new(categories: categories, name: 'Foo')
product.save

jojo43 avatar Jun 01 '20 21:06 jojo43