Has_many, through association

前端 未结 3 386
天涯浪人
天涯浪人 2020-12-17 07:14

Warning:Total Rails Newb (TRN). This should be a pretty basic question so I\'m hoping someone can spare a couple mins to help shed some light.

Let\'s say I have the

3条回答
  •  有刺的猬
    2020-12-17 08:18

    Try this structure:

    class User < ActiveRecord::Base
      has_many :members
      has_many :groups, :through => :members
    end
    
    class Groups < ActiveRecord::Base
      has_many :members
      has_many :users, :through => :members
    end
    
    class Member < ActiveRecord::Base
      belongs_to :group
      belongs_to :user
    end
    

    Also take a look at has_and_belongs_to_many, if you don't need to do with class Member then you should use has_and_belongs_to_many. In this case don't forget to create joining table in the database

提交回复
热议问题