Reputation: 6579
I'm new to ruby on rails. So i think i have association problems.
Given the three model classes with their associations:
# user.rb
class User < ActiveRecord::Base
has_many :product_groups
has_many :products, :through=>:product_groups
end
# product_group.rb
class ProductGroup < ActiveRecord::Base
has_many :products
belongs_to :user
end
# product.rb
class Product < ActiveRecord::Base
belongs_to :product_group
has_one :user
end
So when i trying add new product. I get errors.
# products_controller.rb
def new
@product = current_user.product_groups.products.build
end
The errors I'm receiving is:
NoMethodError (undefined method `products' for #<Class:0x2ca50b0>):
app/controllers/products_controller.rb:27:in `new'
-e:2:in `load'
-e:2
I'm confused, can anybody help me? Or any different idea ?
Upvotes: 2
Views: 95
Reputation: 87210
Given you have the
has_many :products, :through=>:product_groups
you can do just
def new
@product = current_user.products.build
end
Upvotes: 2