【发布时间】:2020-03-06 21:51:58
【问题描述】:
假设我有两个模型:Performance 和 Band,为了连接这两个模型,我有一个名为 performers 的连接表。我的 ActiveRecord 模型设置如下:
class Band < ApplicationRecord
has_many :performers
has_many :performances, through: :performers, dependent: :destroy
end
class Performance < ApplicationRecord
has_many :performers
has_many :bands, through: :performers, dependent: :destroy
end
class Performer < ApplicationRecord
belongs_to :band
belongs_to :performance
end
现在是棘手的部分。我在performers 表中有一个名为permissions 的自定义属性,它捕获表演者的权限级别(所有者、编辑者、查看者),它定义了谁可以对表演进行更改。这让我想到了我的问题:当一个乐队创建一个新的表演时,我如何在创建过程中在连接表上设置一个值,例如
def create
performance = Performance.new(performance_params)
# here I add a performance to a band's performances, which creates a new performer record
band.performances << performance
# what I would also like to do (at the same time if possible) is also define the permission level
# during creation something like but:
performer = band.performers.last
performer.permissions = 'owner'
performer.save
render json: serialize(performance), status: 200
end
Rails 中有什么东西可以让我在创建关联时修改连接表属性吗?
编辑
作为参考,我现在这样做:
def create
performance = Performance.new(performance_params)
performer = Performer.new
performer.band = Band.find(params[:band_id])
performer.permissions = 'owner'
performance.performers << performer
performance.save!
render json: serialize(performance), status: 200
end
但想知道是否有更简单的方法。
【问题讨论】:
标签: ruby-on-rails associations