【问题标题】:rails has_many :through NameErrorrails has_many :通过 NameError
【发布时间】:2013-12-10 20:43:56
【问题描述】:

我有以下设置

class Category < ActiveRecord::Base 

has_many :category_products
has_many :products, through: :category_products

end

class Product < ActiveRecord::Base

has_many :category_products
has_many :categories, through: :category_products

end

class CategoryProducts < ActiveRecord::Base
belongs_to :category
belongs_to :product
end

在 Rails 控制台中,我尝试使用以下命令分配 category_ids p.category_ids = [1,2](其中 p = Product.first)我得到

NameError: uninitialized constant Product::CategoryProduct

有什么建议吗?

谢谢

【问题讨论】:

  • 事实证明,rails 不喜欢连接模型的“多”名称,创建了一个名为 categorization 的新模型,并且所有工作 100%

标签: ruby-on-rails-3 has-many-through


【解决方案1】:

你只是打错了。试试这个:

class Category < ActiveRecord::Base 
  has_many :categories_products
  has_many :products, through: :categories_products
end

class Product < ActiveRecord::Base
  has_many :categories_products
  has_many :categories, through: :categories_products
end

class CategoriesProduct < ActiveRecord::Base # singular association model define
  belongs_to :category
  belongs_to :product
end

注意协会名称。

modelcategories_product(没有s),它是table categories_products

【讨论】:

    【解决方案2】:

    事实证明,rails 不喜欢连接模型的“多”名称,创建了一个称为分类的新模型,并且所有工作 100%

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2017-06-02
      相关资源
      最近更新 更多