Many-to-Many with has_many :through

Posted by Prach on Jul 10, 2009 Tags: rails model

I'm working on my new project and it has many-to-many association. Also, I want to store additional fields in the relation. So, I used has_many :through in my models.

Example:

GIVEN: I have 2 models which are driver and bus. Driver can drive more than one bus and has start time and stop time for each bus. Also, bus can be drived by many drivers. ( Driver will drive particular bus only one period)
I will generate one more model called " Shift " which has bus_id, driver_id, start_time and stop_time. 

Model:

class Shift < ActiveRecord::Base
belongs_to :bus
belongs_to :driver
end
class Driver < ActiveRecord::Base
has_many :shifts
has_many :buses, :through => :shifts
end
class Bus < ActiveRecord::Base
has_many :shifts
has_many :drivers, :through => :shifts
end

Then, how to access start and stop time?

We treat Shiftas one model, so we can use
s = Shift.find_by_bus_id_and_driver_id(busID,driverID)
to get the shift and s.start_time or s.stop_time to access the additional fields.

I love Rails.


comments

Strength, the nation's largest hunger louis vuitton aviator sunglasses advocacy organization. His philanthropic http://www.shoesugg.org/categories/

on trips that coincided with pharrell louis vuitton jewelry court appearances for his drunk <a href=http://www.chanelearrings.org/fake-Louis-Vuitton-Jewelry-136-

taht si itt

There are many big success for the Nike Jordan shoes Jordan shoes to become the famous brand since the first time that the Cheap Jordans Seri

Add your comment here

Your name:*

E-mail:* (will not be shown)

URL:

Comment:*
You might use these HTML tags in your comment: <b>,<I> and <U>

simple_captcha.jpg
(type the code from the image)