Skip to content

Activerecord example

February 10, 2011

At first we create a scaffolds person, employee, designation, company, locations with associations

$ rails new student -d mysql

$ cd student/

$ gedit config/database.yml # set your mysql password in corresponding fields

$ rake db:create

$  rails g scaffold Company name:string

$ rails g scaffold Person name:string

$ rails g scaffold Employee designation:references person:references company:references  #references are make associations

$ rails g scaffold Location company:references address:text city:string

$ rails g scaffold Designation name:string

$ rake db:migrate

$ rails s

Enter the some values in people, designations, companies details

and make drop down list in view layer

Employee View

edit /app/views/employees/_form.html.erb


<div class="field">
<%= f.label :designation %><br />
<%= f.collection_select :designation_id, Designation.all, :id, :name %>
</div>
<div class="field">
<%= f.label :company %><br />
<%= f.collection_select :company_id, Company.all, :id, :name %>
</div>
<div class="field">
<%= f.label :person %><br />
<%= f.collection_select :person_id, Person.all, :id, :name %>
</div>

edit /app/views/employees/show.html.erb

<p>
<b>Designation:</b>
<%= @employee.designation.name %>
</p>
<p>
<b>Company:</b>
<%= @employee.company.name %>
</p>
<p>
<b>Person:</b>
<%= @employee.person.name %>
</p>

edit /app/views/employees/index.html.erb

<td><%= employee.designation.name %></td>
<td><%= employee.company.name %></td>
<td><%= employee.person.name %></td>

Location View
edit /app/views/locations/_form.html.erb

<div class="field">
<%= f.label :company %><br />
<%= f.collection_select :company_id, Company.all, :id, :name %>
</div>

edit /app/views/locations/index.html.erb

 <td><%= location.company.name %></td>

edit /app/views/locations/show.html.erb

<p>
<b>Company:</b>
<%= @location.company.name %>
</p>
 

reload your browser

Advertisements
One Comment leave one →
  1. February 11, 2011 8:17 am

    good example for active records.. it may useful to all rails beginners..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: