I am trying to add categories for some products on Ruby on Rails, but I am getting an error saying NoMethodError: undefined method `categories' for #
Here is my product.rb :
class Product < ApplicationRecord
validates :title, presence: true
has_many :product_categories
has_many :categories, through :product_categories
end
the product category app record:
class ProductCategory < ApplicationRecord
belongs_to :product
belongs_to :category
end
and the category.rb:
class Category < ApplicationRecord
has_many :product_categories
has_many :products, through :product_categories
end
On the interactive ruby shell I give the following commands:
irb(main):006:0> Product.second!
Product Load (0.5ms) SELECT "products".* FROM "products" ORDER BY
"products"."id" ASC LIMIT ? OFFSET ? [["LIMIT", 1], ["OFFSET", 1]]
=> #<Product id: 2, title: "bread", description: "with glutein", price:
0.6e0, created_at: "2019-01-13 19:42:45", updated_at: "2019-01-13
19:42:45">
irb(main):007:0> product= _
=> #<Product id: 2, title: "bread", description: "with glutein", price:
0.6e0, created_at: "2019-01-13 19:42:45", updated_at: "2019-01-13 19:42:45">
irb(main):008:0> product = _
=> #<Product id: 2, title: "bread", description: "with glutein", price:
0.6e0, created_at: "2019-01-13 19:42:45", updated_at: "2019-01-13 19:42:45">
<duct.categories.create!(title: "Bread")
NoMethodError: undefined method `categories' for
Could someone help me understand why this error appears? I am following this tutorial https://www.youtube.com/watch?v=TwoafJC7vlw and it seems to work fine there.
Product
model) & also an indentation(inProductCategory
model). Hope that wasn't the problem. You might wanna check. – Aaditya Maheshwariduct.categories.create!
when you should be doingproduct.categories.create!
– Aaditya Maheshwariduct.categories.create!
is just a copy/paste error. In the title of the question, it says undefined method for product model. – HalilC