Reputation: 1080
I have three models - users, books and contribution.
Each @book will have a title and an author (who owns that instance).
Optionally, each @book can have a number of contributors.
Authors and contributors come from the same class User.
What's the best approach to writing the model relationships? My instinct is
User :name
Book :title :user_id
Contribution :book_id :user_id
users.rb -
has_many :books
has_many :books, through :contribution
books.rb -
belongs_to :user
has_many :users, through :contribution
contributions.rb -
belongs_to :user
belongs_to :book
...but this seems like asking for trouble. Is there a best practice approach to handling models with more than one relationship?
Upvotes: 2
Views: 46
Reputation: 573
I don't know what the full extent of the needs are of your site, but it can be even simpler and just make contributor an attribute of the books model. Books would just have an array of contributors the same way it has a name and an author.
If you have more complex things in mind for the contributor, then maybe making it it's own model is the way to go.
Upvotes: 1
Reputation: 1080
What worked for me was the following -
users.rb -
has_many :books
has_many :contributions
books.rb -
belongs_to :user
has_many :contributions
contributions.rb -
belongs_to :user
belongs_to :book
Upvotes: 0