Recipe 3.6. Accessing Your Data via Active Record


Problem

You have a form that submits its parameters to a controller. Within a method in that controller, you want to create a new Active Record object based on the values of those parameters.

Solution

For example, you have the following authors table as defined in your schema.rb:

db/schema.rb:

ActiveRecord::Schema.define(:version => 1) do   create_table "authors", :force => true do |t|      t.column "first_name", :string     t.column "last_name", :string     t.column "email", :string     t.column "phone", :string   end end

and a corresponding model set up in app/models/author.rb:

class Author < ActiveRecord::Base end

Your author creation form contains the following:

<p style="color: green"><%= flash[:notice] %></p> <h1>Create Author</h1> <form action="create" method="post">   <p> First Name:   <%= text_field "author", "first_name", "size" => 20 %></p>   <p> Last Name:;   <%= text_field "author", "last_name", "size" => 20 %></p>   <p> Email:;   <%= text_field "author", "email", "size" => 20 %></p>   <p> Phone Number:;   <%= text_field "author", "phone", "size" => 20 %></p>   <input type="submit" value="Save"> </form>

Add a create method that creates the new Author object to app/controllers/authors_controller.rb:

def create   @author = Author.new(params[:author])   if @author.save     flash[:notice] = 'An author was successfully created.'     redirect_to :action => 'list'   else         flash[:notice] = 'Failed to create an author.'     render :action => 'new'   end end

Discussion

In the Authors controller, we create a new Author instance by calling Active Record's new constructor. This constructor may be passed a hash of attributes that correspond to the columns of the authors table. In this case, we pass in the author subhash of the params hash. The author hash contains all the values that the user entered into the author creation form.

We then attempt to save the object, which performs the actual SQL insert. If nothing goes wrong, we create a flash message indicating success and redirect to the list action. If the object wasn't saved, perhaps because of validation failures, we render the form again.

See Also

  • Section 3.8"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net