【发布时间】:2020-07-22 08:34:25
【问题描述】:
所以我有 3 个模型 group、recipient 和 group_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