Rails使用附加字段创建/更新连接表

问题描述 投票:0回答:2

加入表

  • 类别(外键)
  • 产品(外键)
  • 等级(整数)

每次我创建/更新时间连接表时,我都要插入排名位置。

模型

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

ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord
2个回答
2
投票

正如@Sean所描述的那样,您需要使用has_many :through关联,因为:

如果需要在连接模型上进行验证,回调或额外属性,则应使用has_many :through2.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}
]

0
投票

您需要使用带有显式模型的has_many :association, through: :through_association作为连接模型。这样您就可以存储关于关联本身的数据。

© www.soinside.com 2019 - 2024. All rights reserved.