繁体   English   中英

Rails 4 ActiveRecord has_many通过关系

[英]Rails 4 ActiveRecord has_many through relation

我无法在Rails / ActiveRecord中找出多对多的产品/类别关系。 我相信我目前已正确设置所有内容,但在尝试创建新关系时,我不断收到以下错误:

uninitialized constant Categorization::ProductId

我的设置如下......

# app/models/product.rb
class Product < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations
end

# app/models/category.rb
class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :products, :through => :categorizations
end

# app/models/categorization.rb
class Categorization < ActiveRecord::Base
  belongs_to :category_id
  belongs_to :product_id
end

如果有帮助,则连接表(分类)的迁移文件是:

# db/migrate/20150924153543_create_categorizations.rb
class Categorizations < ActiveRecord::Migration
  def change
    create_table :categorizations do |t|
      t.integer :product_id
      t.integer :category_id
      t.timestamps null: false
    end
  end
end

我尝试以下任何时候都会收到错误:

Categorization.new(category_id: 1, product_id: 1)

ID的1和1都存在......

我最担心的是关系问题,但是......我目前不得不通过将一个产品与一个类别相关联的单个URL来管理这些问题。 有没有一种简单的方法可以在“添加产品”页面中添加多项选择,以便在创建/编辑产品时可以关联多个? 如果不是,我不会那么担心,因为我的主要关注是如何正常工作。

谢谢!

# app/models/categorization.rb
class Categorization < ActiveRecord::Base
  belongs_to :category
  belongs_to :product
end

您对foreign_keys和ActiveRecord关联感到困惑。

-

product_idcategory_idforeign_keys

在此输入图像描述

它们基本上帮助ActiveRecord在关联的数据表中找到正确的记录。

-

belongs_to :categoryActiveRecord关联

在此输入图像描述

ActiveRecord自动获取category引用并从中构建SQL查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM