I've made a ton of progress in Ruby On Rails. I'm trying to grasp my head around making something with two models/tables. Do you know of any basic tutorials that have two models?
For example I did the Rails for Zombies course and it skims over tweet belongs_to zombie
and zombie has_many tweets
but it doesn't really discuss how to setup that second model or make use of it.
In the little application I'm working on I've now made a model company and model employee and added the company has_many employees
and employee has_one company
but not sure where to go next and could really use a tutorial that covers this. For example I made company like so:
rails g scaffold company name phone website city state twitter
to now make the employee model I did: rails g scaffold employee name phone email
Will the act of associating them automatically add the additional column needed so that employee
has a company_id or should I have created that? And how would I update the employee form so that I can select which company it belongs to?
Quick tutorial:
Let's create a company
rails g scaffold company name
Let's create an employee, and tell Rails that employee will reference the company (will belong to it)
rails g scaffold employee company:references name phone email
Note that in the above command, it is the company:references
that creates the column "company_id" for the employee.
Update your database
rake db:migrate
Let's update the employee form. Change
<%= f.text_field :company %>
to a select box that gets its options from a collection, in this case all Companies
<%= f.collection_select :company_id, Company.all, :id, :name, :prompt => true %>
And, to see the company name, let's edit app/views/employees/show.html.erb
<%= @employee.company.name %>
Finally, edit your app/models/company.rb and add this line
has_many :employees, dependent: :destroy