On Fri, Feb 20, 2009 at 11:19 AM, Guillaume Loader
<[email protected]> wrote:
>
> Hello everyone!
>
> I'm trying to modify an example from a book. The example show how to
> create a scaffold for a table.
>
> But I want to change the way things are modified.
>
> Here is the method in my controller :
>
> def update
> @product = Product.find(params[:id])
>
> respond_to do |format|
> if @product.update_attributes(params[:product])
> flash[:notice] = 'Product was successfully updated.'
> format.html { redirect_to(@product) }
> format.xml { head :ok }
> else
> format.html { render :action => "edit" }
> format.xml { render :xml => @product.errors, :status =>
> :unprocessable_entity }
> end
> end
> end
>
> So I tried to add this line :
>
> Product.title = "You don't decide the title! I do!"
>
> after @product = Product.find(params[:id])
>
> But I got an error (undefined method `title=' for #<Class:0x365b654>)
>
> Could you help me?
>
> Thank you!
Why would you want to do this in the controller (not through user input?)
If it's business logic, it belongs in the model.
You could do something like this in the Product model with callbacks.
class Product < ActiveRecord::base
...
before_save :set_title_my_way
protected
def set_title_my_way
self.title = "this is my title..."
end
end
Then when you do an @product.update_attributes(...) in your
controller, it'll run this before it saves overriding anything passed
in the parameters. It's generally bad-mojo to modify params during the
request.
Additionally, if with ActiveRecord callbacks you can do this before
create, update, or save (depending on how you want to approach this.)
Learn more about callbacks here:
* http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Hope this helps!
Cheers,
Robby
--
Robby Russell
Chief Evangelist, Partner
PLANET ARGON, LLC
design // development // hosting w/Ruby on Rails
http://planetargon.com/
http://robbyonrails.com/
http://twitter.com/planetargon
aim: planetargon
+1 503 445 2457
+1 877 55 ARGON [toll free]
+1 815 642 4068 [fax]
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---