【问题标题】:Rails: flash notice unless only certain attributes updatedRails:闪存通知,除非仅更新某些属性
【发布时间】:2015-08-27 23:59:14
【问题描述】:

我想一直在我的 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

类似这样的伪代码?

【问题讨论】:

  • 我不明白您所说的“除非仅”是什么意思...您是说用户必须更改某些属性吗?他不能让他们保持原样吗?
  • 如果只更改了一个特定的属性,我们称之为photo,我想隐藏闪信。否则我希望它显示出来。
  • 因此,如果他们更改photo 以及其他一些属性,您希望看到该消息。如果他们没有更改photo,但他们更改了其他一些属性,您希望看到该消息。如果他们更改了photo 但没有更改任何其他内容,那么您不想看到该消息。对吗?
  • 完全正确,是的。
  • 您是否需要完全更新它,或者您是否想提醒他们上传照片以便在照片未上传时显示?

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

使用changed 方法获取已更改属性的数组,如果属性不是“非通知”属性,则创建一个闪烁消息。

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

如果他们更改了photo 和其他属性,或者如果他们更改了其他属性但没有更改photo,这将显示saved 通知。仅当 photo 更改时,消息才会被抑制。

【讨论】:

  • 完美!非常感谢。
  • 我知道这不是问题的一部分,但我认为值得注意的是:这不适用于 NESTED ATTRIBUTED
  • 所以将其添加到 changed_fields 列表中...changed_fields = (@user.changed + @user.name_of_nested_associations.map(&:changed)).flatten
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2020-09-18
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多