开发者

Whats the cleanest way to handle many-to-many relationships in ruby on rails?

开发者 https://www.devze.com 2023-01-08 07:48 出处:网络
I have one model say user, that can live in multiple towns (represented as another model).If I create a new user I have to choose (and edit) the different towns that they live in. Due to time constrai

I have one model say user, that can live in multiple towns (represented as another model). If I create a new user I have to choose (and edit) the different towns that they live in. Due to time constraints, I often end up with a "hackyier th开发者_Python百科an I would like" solution involving something like: http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off.

Any nice solutions that are popular with SO?

cheers...

Slothishtype


The has_and_belongs_to_many association was built for this very situation. Here is the documentation on it: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

Otherwise, if you need to store information abotu the association itself (fields that would not exist in the city table or the user table, but in between), you might just want to set up two, parallel 'has_many_through' associations, and set up a seperate 'user_city' table. So it would be in the user table

has_many :user_cities
has_many :cities, :through => :user_cities

and in the cities table

has_many :user_cities
has_many :users, :through => :user_cities

Then, you CAN just call: user.cities, and get a list of the cities the user lives in.

0

精彩评论

暂无评论...
验证码 换一张
取 消