简体   繁体   English

Rails:创建新记录时更新连接表自定义属性

[英]Rails: Update join table custom attribute when a new record is created

Lets say I have two models: Performance and Band , and to connect the two I have a join table called performers .假设我有两个模型: PerformanceBand ,为了连接这两个模型,我有一个名为performers的连接表。 My ActiveRecord models are setup as follows:我的 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

Now the tricky part.现在是棘手的部分。 I have a custom attribute called permissions in the performers table that captures the permission levels (owner, editor, viewer) for a performer, which defines who can make changes to a performance.我在performers表中有一个称为permissions的自定义属性,它捕获performers的权限级别(所有者、编辑者、查看者),它定义了谁可以对表演进行更改。 Which brings me to my question: when a band creates a new performance, how can I set a value on the join table during creation eg这让我想到了我的问题:当一个乐队创建一个新的表演时,我如何在创建过程中在连接表上设置一个值,例如

    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

Is there something in Rails that can let me modify a join tables attribute during creation of an association? Rails 中有什么东西可以让我在创建关联期间修改连接表属性?

EDIT编辑

For reference, right now I do:作为参考,现在我这样做:

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

But was wondering if there was something simpler.但想知道是否有更简单的东西。

You can use either Association Callbacks on has_many or add appropriate callback to Performer model as it's still created as a model even it's joining one.您可以在has_many上使用关联回调或向Performer模型添加适当的回调,因为即使它正在加入模型,它仍然作为模型创建。

Something like:就像是:

class Performer < ApplicationRecord
  belongs_to :band
  belongs_to :performance

  before_create :set_permissions

  private

  def set_permissions
    self.permissions = 'owner'
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM