Background: I'm trying to add an edit function to user data on a website. I have it currently setup so a user can click edit and the user is taken to a new page with text fields already populated with their existing information. They can then make changes and click update.
What I wanted to do is figure out which text fields have different text, from what they were originally populated with, and only update those fields (only update attributes that are different from before). Then keeping track of what fields have been updated alert the user (for instance: "changes have been made to: first name, last name)"
Code Ruby:def edit_manage @user_info = User.find_by_id(session[:user_id]) updated = [] if request.post? @update = User.find_by_id(session[:user_id]) @update.update_attributes(params) #collect original values to compare later t = {:first_name => @update.first_name, :middle_name => @update.middle_name, :last_name => @update.last_name, :email => @update.email, :about => @update.about} params.each do |key,value| if t[key] != value #is the original value different from the new? @update.update_attribute(key,value) updated << key.to_s end end changed = '' updated.each_with_index do |value,index| changed << ', ' unless index.zero? changed << value end flash[:notice] = "#{changed} updated" redirect_to :action => 'manage' end end
Needless to say this doesn't work and I'm guessing there is a much easier way to do this.
===
got it to work by doing the following:
Code Ruby:def edit_manage @user_info = User.find_by_id(session[:user_id]) if request.post? @update = User.find_by_id(session[:user_id]) t = {:first_name => @update.first_name, :middle_name => @update.middle_name, :last_name => @update.last_name, :email => @update.email, :about => @update.about} updated = [] t.each do |key,value| if value != params[key] @update.update_attribute(key,params[key]) updated << key.to_s end end changed = '' updated.each_with_index do |value,index| changed << ', ' unless index.zero? changed << value end flash[:notice] = "Updated: #{changed}" redirect_to :action => 'manage' end end
However, I'm still looking for a more efficient way of doing that!




Bookmarks