Skip to content

Relationship concepts in rails 3

March 10, 2011

Mr. Thayagarajan taught  relationship between the models

Relationships are

has_many ,  belongs_to ,  has_and_belongs_to_many ,  has_many through

rails script  is easy to write because it has english grammar

1. has_many, belongs_to

Example :   we take a company , A Company has many  Employees , Employees are belongs to Company

using this sentance to write relationship script in model

app/model/company.rb


class Company < ActiveRecord::Base

has_many :employees

end

app/model/employee.rb


class Employee < ActiveRecord::Base

belongs_to :company

end

2. has_and_belongs_to_many

Example :  Bank has many Customers and also Customer has many Banks (accounts)

app/model/bank.rb

class Bank < ActiveRecord::Base
    has_and_belongs_to_many :customers
end
app/model/customer.rb
class Customer < ActiveRecord::Base
  has_and_belongs_to_many :banks
end
in bank_customer_join migration table we define the conditions
db/migration/2011….bank_customer_join.rb
class bank_cutomer_join < ActiveRecord::Migration
    def self.up
        create_table :bank_customer_join, :id => false  do |t|
            t.integer :bank_id
            t.integer :customer_id
            t.timestamps
        end
    def self.down
    .........
end
end
In this join table has only the two way join table and without table id, this relationship does not allow the third one
3. has_many through
it makes a n way joint table, easy to retrive the info’s or data’s in that joint table
create a rails application
and create  a models
$ rails g model Applicant name:string address:string
$ rails g model Mandate name:string
$ rails g model Interview applicant_id:integer mandate_id:integer description:string     #it is a joint table of applicant and mandate tables
app/models/applicant.rb
class Applicant < ActiveRecord::Base
  has_many :interviews
  has_many :mandates, :through => :interview
end
app/models/mandate.rb
class Mandate < ActiveRecord::Base
  has_many :interviews
  has_many :applicants, :through => :inerview
end<
app/models/interview.rb
class Interview < ActiveRecord::Base
  belongs_to :applicant
  belongs_to :mandate
end
$ rake db:create
$ rake db:migrate
$ rails console
in rails console we insert a applicant data’s
use the above steps again and again to insert more data’s via console
insert mandate data’s
insert interview data as the joint table
In Databases
Advertisements
One Comment leave one →
  1. October 23, 2013 1:01 pm

    good

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: