NoMethodError:#<产品:0x00000000070a9810>的未定义方法'类别'

时间:2019-01-13 20:17:53

标签: ruby-on-rails ruby activerecord

我正在尝试在Ruby on Rails上为某些产品添加类别,但是出现错误,提示 NoMethodError:#

的未定义方法'categories'

这是我的产品。rb:

 class Product < ApplicationRecord

  validates :title, presence: true

  has_many :product_categories
  has_many :categories, through :product_categories
 end

产品类别应用记录:

class ProductCategory < ApplicationRecord

  belongs_to :product
  belongs_to :category

end

和category.rb:

class Category < ApplicationRecord
  has_many :product_categories
  has_many :products, through :product_categories
end

在交互式红宝石外壳上,我给出以下命令:

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 

有人可以帮助我理解为什么出现此错误吗?我正在按照本教程 https://www.youtube.com/watch?v=TwoafJC7vlw 进行操作,似乎可以正常运行。

1 个答案:

答案 0 :(得分:1)

Product模型中,请将has_many :categories, through :product_categories更改为has_many :categories, through: :product_categories。您需要在through之后添加一个冒号。与Category模型相同。这应该可以解决错误。

此外,您还有一些其他语法错误/错别字,例如在产品模型validates中写为valitates