【问题标题】:Rails create / update join table with additional fieldRails 使用附加字段创建/更新连接表
【发布时间】:2019-02-25 22:42:42
【问题描述】:

加入表格

  • 类别(外键)
  • 产品(外键)
  • 排名(整数)

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

型号

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


    【解决方案1】:

    正如@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}
    ]
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 好的,我知道了。如何批量插入/更新记录?例如。 [{类别:A,产品:X,排名:1},{类别:A,产品:Y,排名:2},..]
      猜你喜欢
      • 2015-12-02
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 2018-12-07
      • 2015-09-18
      相关资源
      最近更新 更多