我想一直在我的Rails应用中显示Flash通知,除非某些属性已更新。
def update
if @user.update_attributes(user_params)
if user_params == [:user][:certain_params]
redirect_to users_path
else
redirect_to users_path, notice: "#{@user.name} saved."
end
else
redirect_to edit_user_path(@user), flash: { error: @user.mapped_errors }
end
end
像这样的伪代码?
答案 0 :(得分:2)
使用changed
方法获取已更改属性的数组,如果属性不是"非通知"则创建Flash消息。属性。
def update
@user.assign_attributes(user_params)
changed_fields = @user.changed
if @user.save
flash[:notice] = "#{@user.name} saved." if changed_fields != ["photo"]
redirect_to users_path
else
redirect_to edit_user_path(@user), flash: { error: @user.mapped_errors }
end
end
如果他们更改saved
加上其他属性,或者他们更改了其他属性但不更改photo
,则会显示photo
通知。仅当仅 photo
发生更改时,才会禁止该消息。
答案 1 :(得分:0)
def update
@user = User.find(params[:id])
# lets say you have these attributes to be checked
attrs = ["street1", "street2", "city", "state", "zipcode"]
attributes_changed = (@user.changed & attrs).any?
if @user.update_attributes(user_params)
flash[:notice] = "#{@user.name} saved." if attributes_changed
redirect_to users_path
else
redirect_to edit_user_path(@user), flash: { error: @user.mapped_errors }
end
end
有关详情,请参阅
Rails 3 check if attribute changed
http://api.rubyonrails.org/classes/ActiveModel/Dirty.html