【问题标题】:Change params value on model callback更改模型回调的参数值
【发布时间】:2020-07-22 08:34:25
【问题描述】:

所以我有 3 个模型 grouprecipientgroup_recipients

class Group < ApplicationRecord
    has_many :group_recipients, dependent: :destroy
    has_many :recipients, through: :group_recipients
end

class GroupRecipient < ApplicationRecord
    belongs_to :recipient, inverse_of: :group_recipients, autosave: true
    belongs_to :group
end

class Recipient < ApplicationRecord
    has_many :group_recipients, inverse_of: :recipient, autosave: true, dependent: :destroy
    has_many :groups, through: :group_recipients
end

控制器#update recipients_controller.rb

def update
 @recipient = Recipient.with_deleted.find(params[:id])
 if @recipient.update(recipient_params)
  respond_to do |format|
    redirect_url = params[:commit] == 'Save and add another' ? new_recipient_path : edit_recipient_path(@recipient)
    format.html { redirect_to redirect_url, notice: 'Recipient was successfully updated.' }
    format.json { render json: {status: :success} }
  end
else
  respond_to do |format|
    format.html { render :edit }
    format.json do
      render json: {
        status: :error,
        recipient: @recipient,
        errors: @recipient.errors
      }
    end
  end
end
end

 def recipient_params
   params.require(:recipient).permit(
   :email_address, :first_name, :last_name, :language_id,
   :phone, group_ids: [])
 end

在收件人update,收到params[:group_ids]。在这里,在before_update 回调中,我希望能够通过一些逻辑更改group_ids 值。我可能需要在 group_ids 数组中添加或删除数据。

问题是 activerecord 根据params[:group_ids] 更新所有组,即使我更改它。我在回调之前还是之后使用它都没有关系。一旦我在self.group_ids 中设置了值,它确实会进行这些更改,但是一旦事务完成,它会再次恢复这些更改。

【问题讨论】:

  • 请分享控制器方法。
  • @RipTheJacker 我已经添加了控制器方法。

标签: ruby-on-rails ruby activerecord callback


【解决方案1】:

在回调 before_update 中进行更新的想法不好,你会遇到递归错误的问题。另一种方法是根据控制器中的逻辑更改参数,然后您可以使用正常的更新方法。

【讨论】:

  • 是的,但我不想在回调中更新。我只想在模型回调中赋值。
  • 您可以像这样在回调中分配属性。 before_update :function_name def function_name self.attribute = something end
  • 这确实有效,但是一旦交易完成,它就会被还原。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 2018-03-13
相关资源
最近更新 更多