addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobegmailgooglegroupshelp-with-circleimageimagesinstagramlinklocation-pinm-swarmSearchmailmessagesminusmoremuplabelShape 3 + Rectangle 1ShapeoutlookpersonJoin Group on CardStartprice-ribbonShapeShapeShapeShapeImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruserwarningyahoo

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

People in this
Meetup are also in:

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