我已经建立了以下关联:
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
endBookLaunchLocation有一个名为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发布于 2020-10-21 04:07:29
如果您想创建一个只包含两个以上外键列的连接模型行,则需要显式地而不是隐式地创建它。
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)https://stackoverflow.com/questions/64452393
复制相似问题