1

I want to show a flash notice in my Rails app all the time unless only certain attributes are updated.

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

Something like this pseudocode?

t56k
  • 6,769
  • 9
  • 52
  • 115
  • I don't understand what you mean by "unless only"... are you saying that the user must change certain attributes? He's not allowed to leave them unchanged? – SteveTurczyn Aug 28 '15 at 00:27
  • If only one particular attribute is changed, let's call it `photo`, I want to hide the flash message. Otherwise I want it shown. – t56k Aug 28 '15 at 00:38
  • So if they change `photo` plus some other attribute, you want to see the message. If they don't change `photo` but they change some other attribute, you want to see the message. If they change `photo` but don't change anything else, you *don't* want to see the message. Is that right? – SteveTurczyn Aug 28 '15 at 00:40
  • That's exactly right, yeah. – t56k Aug 28 '15 at 00:43
  • Do you need it exactly updated or are you trying to remind them to upload a photo so you want that shown if the photo is not uploaded? – dinomix Aug 28 '15 at 00:50

2 Answers2

2

Use the changed method to get an array of the attributes that are changed, create a flash message if the attributes are not the "non-notify" attributes.

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

This will show the saved notice if they change photo plus other attributes, or if they change other attributes but not photo. The message is suppressed only if only photo is changed.

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
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

For more info see
Rails 3 check if attribute changed
http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

Community
  • 1
  • 1
Shiva
  • 11,485
  • 2
  • 67
  • 84