所以我有三个模型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
控制器#更新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
中设置了值,它就会进行这些更改,但一旦事务完成,它就会再次恢复这些更改。
在回调before_update中进行更新的想法不好,您会遇到递归错误的问题。另一种方法是根据控制器中的逻辑更改参数,然后可以使用正常的更新方法。