Re: [ruby-81] copying and comparing model objects

From: Loqi
Sent on: Tuesday, March 4, 2008 9:03 PM
Oops, I just noticed I'm still a bit confused with this controller 
code from William:

01 def update
02   @product = Product.find(params[­:id])
03   @product.update_attr­ibutes(params[:produ­ct])
04   if !@product.changed?
05     flash[:notice] = "You haven't changed anything."
06     redirect_to :action => 'show', :id => @product
07   else
08     if @product.save
09       flash[:notice] = "Product was successfully updated."
10       redirect_to :action => 'show', :id => @product
11     else
12       render :action => 'edit'
13     end
14   end
15 end

The motivation for comparing the data is to avoid writing to the DB 
unless the user actually changed something. Line 3 above calls 
update_attributes, which (I think) includes a write to the DB.  Line 
8 also writes to the DB. Is this what you meant to do, Will?

Is the version below correct? Only line 7 writes to the database.

01 def update
02   @product = Product.find(params[­:id])
03   if !@product.changed?
04     flash[:notice] = "You haven't changed anything."
05     redirect_to :action => 'show', :id => @product
06   else
07     if @product.update_attr­ibutes(params[:produ­ct])
08       flash[:notice] = "Product was successfully updated."
09       redirect_to :action => 'show', :id => @product
10     else
11       render :action => 'edit'
12     end
13   end
14 end

I'm pretty sure this will work, but I'm still not so confident with Rails.

Our Sponsors

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy