通过Rails在has_many上添加其他属性

问题描述

我已经建立了以下关联:

class BookLaunch < ApplicationRecord
  has_many :book_launch_locations,dependent: :destroy
  has_many :stores,through: :book_launch_locations
    
....

class Store < ApplicationRecord

  has_many :book_launch_locations
  has_many :book_launch,through: :book_launch_locations

....

class BookLaunchLocation < ApplicationRecord
  belongs_to :book_launch,:touch => true
  belongs_to :store
end

BookLaunchLocation具有一个名为book_price属性

  create_table "book_launch_locations",id: :integer,options: "ENGINE=InnoDB DEFAULT CHARSET=utf8",force: :cascade do |t|
    t.integer "book_launch_id",null: false
    t.integer "store_id",null: false
    t.integer "book_price",default: 1,null: false
    ...
    t.index ["book_launch_id","store_id"],name: "pair_uniqueness",unique: true
    t.index ["book_launch_id"],name: "index_book_launch_locations_on_book_launch_id"
    t.index ["store_id"],name: "index_book_launch_locations_on_store_id"
  end 

我想将book_price添加到BookLaunch模型中的存储中,以便在我调用@book_launch.stores,它将具有商店的所有属性+ book_price属性

这可能吗?

我使用fastJsonApi这样称呼它:

    options = {
      include: [:book_launch,:'book_launch.properties']}
    json = Api::launchSummarySerializer.new(summaryData,options).serialized_json

    render json: json

解决方法

如果要创建一个包含更多行的联接模型行,则只需显式而不是隐式即可创建它。

store = Store.first
book_launch = BookLaunch.first

BookLaunchLocation.create(
  store: store,book_launch: book_launch,price: 999
)

# or
store.book_launch_locations.create(
  book_launch: book_launch,price: 999
)

# or
book_launch.book_launch_locations.create(
  store: store,price: 999
)

隐式创建连接模型行是通过间接关联创建的:

Store.first.book_launches.create!(attributes)
BookLaunch.first.stores.create!(attributes)