【问题标题】:Rails: Update join table custom attribute when a new record is createdRails:创建新记录时更新连接表自定义属性
【发布时间】: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


    【解决方案1】:

    您可以在has_many 上使用Association Callbacks 或将适当的callback 添加到Performer 模型,因为即使它正在加入模型,它仍然是作为模型创建的。

    类似:

    class Performer < ApplicationRecord
      belongs_to :band
      belongs_to :performance
    
      before_create :set_permissions
    
      private
    
      def set_permissions
        self.permissions = 'owner'
      end
    end
    

    【讨论】:

    • 如果权限在创建时始终是“所有者”,则此方法有效,但如果在另一个控制器中我想将表演者添加到现有表演中但我希望该表演者只是“观众”怎么办?
    • 我会说你最后的 sn-p 是最好的方法。您可以将我的解决方案扩展到诸如在performance 上查找虚拟属性并将其设置在控制器中,但我想它会更加混乱。如果规则是静态的 - 第一个 owner 其余是 viewers,您可以在 set_permissions 中查找它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2012-09-24
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多