Reputation: 26494
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.
Upvotes: 0
Views: 1520
Reputation: 19131
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.
Upvotes: 2