问题
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 !
回答1:
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:
create_table :boats_and_pros do |t|
t.belongs_to :user, index: true
t.belongs_to :pro_user, index: true
t.timestamps
end
Then in the corresponding boats_and_pros.rb Model file you'll add:
belongs_to :user
belongs_to :pro_user
In your user.rb
file you'll add:
has_many :boats_and_pros
has_many :pro_users, through: :boats_and_pros
In your pro_user.rb
model file you'll add
has_many :boats_and_pros
has_many :users, through: :boats_and_pros
Two key takeaways are:
- The "oldschool"
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. - One-to-many relationships like what you ended up with on your original attempt keep the reference in one of the tables while many-to-many relationships require a third join table as shown above.
来源:https://stackoverflow.com/questions/43590522/how-to-do-a-has-many-relation-on-two-tables