One of the first thing I encounter was to find a way how to associate tables. The simples association could be for example this:
You have several books represented by the
Book object and stored in the
books table in the DB. This books have a status that could be
Available, Borrowed or Missing. Now, in order to represent that in Rails you need to create those two classes and associate them so in the View you can select from a drop down list the correct status.
Let's start creating a rails project, open your console and type:
rails new library
cd library
create the objects
rails g scaffold Book name:string status_id:integer
rails g scaffold Status name:string
create the tables for each object
In the models you have to add the association for each class.
For book:
class Book < ActiveRecord::Base
attr_accessible :name, :status_id
belongs_to :status
end
For status:
class Status < ActiveRecord::Base
attr_accessible :name
has_one :book
end
Now if run the server with:
rails s
and if you go to the following address you will be able to create the three statuses required
http://localhost:3000/statuses
and then go to the url:
http://localhost:3000/books/new
you will see that instead of having status, you have the index, but this is not what we want.
for having the name of the status you have to change something in the view of the book
From your editor open the file app/views/books/_form.html.erb
and this is the code we have to change:
<div class="field">
<%= f.label :status_id %><br />
<%= f.number_field :status_id %>
</div>
by this one, which basically creates the drop down list for you:
<div class="field">
<%= f.label :status_id %><br />
<%= collection_select :book, :status_id, Status.all, :id,:name,:promp => true %>
</div>
The signature of collection_select is this:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
Basically the two first parameters of collection_select indicate where do you want to save the selection. In this case: Book.status_id
Status.all retrieves all the values from the status table and loads them into the drop down list.
The following two parameters indicate how to create the drop down list, the first is the value, which is the index or primary key of the status, and the second is the text which is the name of the status
For more information on how to use collection select, check out the
documentation