加入表
每次我创建/更新时间连接表时,我都要插入排名位置。
模型
class Category < ApplicationRecord
has_and_belongs_to_many :products
class Product < ApplicationRecord
has_and_belongs_to_many :categories
Schema.db
create_table "products_categories", id: false, force: :cascade do |t|
t.bigint "category_id", null: false
t.bigint "product_id", null: false
t.integer "rank"
t.index ["category_id", "product_id"], name: "index_products_categories_on_category_id_and_product_id"
end
我知道我能做到这一点。但是我怎样才能通过等级值?
c = Category.find(1)
c.products = array_of_products
c.save
Rails 5.2
正如@Sean所描述的那样,您需要使用has_many :through
关联,因为:
如果需要在连接模型上进行验证,回调或额外属性,则应使用
has_many :through
。 2.8 Choosing Between has_many :through and has_and_belongs_to_many
例如,要创建一个连接模型rank
(我不能提出一个比排名更好的名字,抱歉!):
# join table migration
class CreateRanks < ActiveRecord::Migration[5.2]
def change
create_table :ranks do |t|
t.references :product
t.references :category
t.integer :rank
t.timestamps
end
end
end
你的型号:
# product.rb
class Product < ApplicationRecord
has_many :ranks
has_many :categories, through: :ranks
end
# rank.rb
class Rank < ApplicationRecord
belongs_to :product
belongs_to :category
end
# category.rb
class Category < ApplicationRecord
has_many :ranks
has_many :products, through: :ranks
end
因此,您可以“批量”创建记录,如下所示:
Rank.create [
{ category: a, product: x, rank: 1},
{ category: b, product: y, rank: 2}
]
您需要使用带有显式模型的has_many :association, through: :through_association
作为连接模型。这样您就可以存储关于关联本身的数据。