开发者

Rails - Model Doubt

Given the fact that I have models like this:

class Person
  has_many :owned_groups, :class_name => "Group", :foreign_key => :owner_id
  has_many :owned_group_memberships, :through => :owned_groups, 
              :source => :group_memberships 

  has_many :group_memberships, :foreign_key => "member_id"
  has_many :groups, :through => :group_memberships

end

cla开发者_StackOverflowss GroupMembership
  belongs_to :member, :class_name => 'Person'
  belongs_to :group
end

class Group
  belongs_to :owner, :class_name => "Person"
  has_many :group_memberships
  has_many :members, :through => :group_memberships
end

How can I access the members a group has? Always I do @group.members or things like that, gives me an error saying that the relation can't be found in the model.

Thanks in advance.

##EDIT##

The error I'm getting is: Could not find the association "group_memberships" in model Group


I do a similar thing on a site I'm working on but the associations are a little different to how you're doing it but maybe it'll help. I think you need to use the has_and_belongs_to_many association to join up your many-to-many's.

In my database I have Users, Members and UsersMembers

You don't need to create a UsersMembers model (GroupMembership in your case) but you do need a database table to link the two.

#Migration
    create_table :bands_users, :id => false, :force => true do |t|
      t.integer :band_id,       :null => false
      t.integer :user_id,       :null => false
    end

#Models
  class Band < ActiveRecord::Base
    has_and_belongs_to_many :members, :class_name => 'User'
  end

  class User < ActiveRecord::Base
    has_and_belongs_to_many :bands
  end

From this I can now call @band.members or @user.bands


You may need to specify :class_name => 'Person' in your has_many :members statement.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜