I am a noob starting out with ruby on rails and trying to understand models. Pretty familiar with databases and wanted to understand when to generate models for a relationship?
For example - I have users table and gadgets table. Every user can have multiple gadgets. I want to store this relationship in a relationship table with user_id and gadget_id. I have created the two tables by using the rails generate model User and rails generate model Gadget cmd.
Question - Will I now create another model called users_gadgets ? Is the naming convention correct? I have seen lots of documentation on how to create associations (has_many, belongs_to ) but don't understand when I need to create model?
Do I have to create models every time I want to store a relationship in a database and then run my migrations?
A relation model only makes sense for a N-to-N relationship as you described it. When you choose to use has_and_belongs_to_many, you don't need to create a join model, but you still have to create the join table via a migration. The naming convention is then gadgets_users, because 'g' is before 'u' in the alphabet.
If you chose has_many :through, you could store additional information within the join table via a GadgetUser join model. For example if you wanted to record that a gadget belonged to a user for a given time, then this time information logically belongs to the "connection" between gadget and user so you should keep it in the join table.
you can do it one of two ways
1) has_and_belongs_to_many in this case you just need a table (no model) gadgets_users with user_id gadget_id, rails likes the table names to be plural in alpha order
2) has_many :through, this is not a 'normal' has many, in this case you would need a model (can be named whatever you like) i prefer this one over the other because it allows you to add additional attributes to the relationship if needed
see the guide, it does a way better job explaining than I can http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many
also - railscasts - http://railscasts.com/episodes/47-two-many-to-many
Do I have to create models every time I want to store a relationship in a database and then run my migrations? Yes, most of the time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With