0
votes

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.

1
I edited your post to fix a spelling in the code(Product model) & also an indentation(in ProductCategory model). Hope that wasn't the problem. You might wanna check.Aaditya Maheshwari
Also, you are doing duct.categories.create! when you should be doing product.categories.create!Aaditya Maheshwari
@AadityaMaheshwari I think the duct.categories.create! is just a copy/paste error. In the title of the question, it says undefined method for product model.HalilC
@HalilC Yeah. Correct.Aaditya Maheshwari

1 Answers

1
votes

In the Product model please change has_many :categories, through :product_categories to has_many :categories, through: :product_categories. You need to add a colon after through. Same in Category model. This should solve the error.

In addition you have some other syntax errors / typos, for example in product model validates is written as valitates.