Rails - Model Doubt

冷暖自知 提交于 2019-12-13 05:16:47

问题


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

class 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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/6090632/rails-model-doubt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!