开发者

Many to Many Question/Problem!

How does rails handle many to many relationships?

I am tryin开发者_运维技巧g to create a user which can get assigned a pre defined group from the groups table.

Which is what the user_group table is for.. how is this done?

Picture of ERD below

http://i.imgur.com/rGzLO.png


Quick primer on Rails relationships -

1:n - Has Many
n:1 - Belongs To
n:n - Has And Belongs To Many (HASBTM)

For your specific situation, simply call has_and_blongs_to_many from both your User and Group classes -

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
end


Railscast on many to many and another one that should work with your DB

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜