views:

281

answers:

1

I am trying to create an intermediate model between two models that I'd like to have a many to many relationship. I am creating an atypical book checkout project and have two models setup Book and Person. I'd like to setup an intermediate model BookCheckOut to track OutDate and ReturnDate.

Dan Singerman provided what looks like the answer I am looking for to the question Ruby On Rails Relationships - One to Many. My inexperience with out model generation and my reliance upon scaffolding are probably causing my problem. I am trying to determine how to not only generate the model but a working database migration that would accompany it.

+1  A: 

I am not a rails maestro, but there are two ways to do it that I know of: has_many :through and has_and_belongs_to_many. This article has a decent overview of how. I suspect you would want to use has_many :through so you can access the data in the join table cleanly.

To generate the intermediate model you would do something like:

script/generate model checkouts person_id:int, book_id:int, checked_out:date, returned:date

In your Book model you would add (does Rails know Person --> "People"? I'm guessing yes):

has_many :people, :through => :checkouts
has_many :checkouts, :dependent => true

In your Person model you would add:

has_many :books, :through => :checkouts
has_many :checkouts, :dependent => true

In your Checkout (sorry, I renamed it from your example) model, you would add:

belongs_to :person
belongs_to :book

Use caution with my examples - I am going from memory.

SingleShot
Great article, it certainly explains the options. That said if I choose *Join Model: Rich Associations* how do I go about generating the model and database migration? Do I just generate a model containing the ids of the book and person tables. Add the belongs_to :XXXXX to my intermediate model and the has_many :XXXXX to the others?
ahsteele
I updated my answer.
SingleShot
I was getting errors when I had the :dependent => symbol added. I removed it and was able to get the application to work. What is the intention behind the :dependent => ?
ahsteele