I’ve found some good information on STI but have not seen examples for what I want to do. This is the best example I can think of. I want to be able to track two entities but they don’t need their own tables. I need only distinguish type (STI can do this) but I also need to know if and how one entity is related to another. I’ll use books as an example. Some books are just books but other physical books are collections of multiple books.
table: books
id | title | author_id | book_id
1, 'Fellowship of the Ring, 34, (NULL) # is a physical book
2, 'The Two Towers', 34, (NULL) # is a physical book
3, 'American Gods', 1, (NULL) # is a physical book
4, 'Complete Lord Of the Rings', 34, (NULL)
5, 'Fellowship of the Ring', 34, 4 # is collected within book id 4
6, 'The Two Towers', 34, 4 # is also collected within book id 4
etc.
So I want to be able to query books, for all books and understand how and if they are related to each other by ‘book_id’
Is this possible in Rails? If so, how is it best implemented? Can I say ‘has_many :books’ in the books model? Are their gotchas or concerns, etc.?
Thank you in advance.
something like this might work for your situation?
then when querying
you might find that you really want your models to be different ?
Series and Book and not use STI? it would make the queries across both more complex but might make the rest of the application easier to understand
UPDATE: added belongs_to to the PhysicalBook, class name on the has_many association
The book database table ends up looking something like
ALSO: read this – http://rhnh.net/2010/07/02/3-reasons-why-you-should-not-use-single-table-inheritance
you might not want STI ? data model would look similar to above but without the STI, i.e. Series / Book
use of foreign_key in has_many and belongs_to can be confusing: read up on that here – http://guides.rubyonrails.org/association_basics.html