t56k
t56k

Reputation: 6981

Rails: flash notice unless only certain attributes updated

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?

Upvotes: 1

Views: 418

Answers (2)

Shiva
Shiva

Reputation: 12524

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

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

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.

Upvotes: 2

Related Questions