I'm trying to do a has_many relation with a table on creation and also to add it in another table already created.
I have my User
table already with no relations.
I want to create a Pro_user
with a relation has_many User
.
The thing is that one User
can have multiple Pro_user
and a Pro_user
can also also have multiple User
.
So both tables need a has_many
right ?
So what I thought of was that
rails g model pro_user name:string email:string password_digest:string user:references
But this is not the right thing, it's doing a belongs_to
from Pro_user
to User
And also how should I do to do add the has_many on my existing table User
? Do I have to do a migration to recreate the table and adding the relation ?
Thanks for your help !
The recommended approach for a many to many association is the "
has_many_through
" approach. This allows you to add additional columns later on to the join table if you need more data. You'll need a join table that will at the least have two reference columns to your Users and ProUsers tables along with the standard id column. (Refer to: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association)So your User and ProUser tables will not have any reference columns in them. Instead you'll make a third table called BoatsAndPros (call it whatever you like) and do:
Then in the corresponding boats_and_pros.rb Model file you'll add:
In your
user.rb
file you'll add:In your
pro_user.rb
model file you'll addTwo key takeaways are:
has_and_belongs_to_many
approach is still fine however doesn't allow room to grow like the has_many_through approach here and you'll need to specifically name the table pro_users_users because Rails expects the two tables to be listed in lexical order.