Ruby on rails NoMethodError:
我试图为RubyonRails上的一些产品添加类别,但是我得到了一个错误,即NoMethodError:undefined方法'categories' 这是我的产品。rb:Ruby on rails NoMethodError:,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我试图为RubyonRails上的一些产品添加类别,但是我得到了一个错误,即NoMethodError:undefined方法'categories' 这是我的产品。rb: class Product < ApplicationRecord validates :title, presence: true has_many :product_categories has_many :categories, through :product_categories end
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
在交互式ruby shell上,我给出以下命令:
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
有人能帮我理解为什么会出现这个错误吗?我正在学习本教程,它在那里似乎工作得很好。在产品模型中,请将has\u many:categories,through:Product\u categories更改为has\u many:categories,through::Product\u categories。通过后需要添加冒号。在类别模型中相同。这应该可以解决这个错误
此外,您还有一些其他语法错误/拼写错误,例如,在产品模型中,validates是作为valitates编写的 我编辑了您的帖子,以修复codeProduct模型中的拼写问题,以及ProductCategory模型中的缩进问题。希望这不是问题所在。您可能需要检查。此外,您正在执行风管.categories.create!当您应该执行product.categories.create时@AadityaMaheshwari我认为风管.categories.create!只是复制/粘贴错误。在问题的标题中,它说产品模型的未定义方法。@HalilC是的。对的