Has_many, through association

前端 未结 3 400
天涯浪人
天涯浪人 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:17

    basically has_many-through associations are n:m associations (join-tables) that (shall) have more attributes than just the id's of the joined record ids...

    so you have a table Groups (with an id), a table Users (with an id) and a table Members (no id, but user_id and group_id)

    basically, what you did is nearly correct, just think about how you access a group from a user or vice versa....

    a user would first look up its member information and through that member information get access to the group information ... and vice versa for a group

    so you first set up

    has_many :members
    

    and then call

    has_many :groups, :through => :members
    

    all you need is

    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
    

    and you have another bug in your code above

    you might want to use

    user = group.users.new
    

    instead of

    user = group.user.new
    

提交回复
热议问题