简体   繁体   中英

Rails - multiple associations to same model

I'm building a Rails app to track expenses/debts among members of a group, let's say a household. So far I have models for Groups, Users and Expenses - the basics. Right now I'm trying to figure out the associations between Groups and Users. For example, a Group can have many users and a user can have/belong to many groups, so I set a HABTM association using a join table. But I'm confused because a Group can also have one owner, which is also a User. This is where I am right now:

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
    has_one :owner, :class_name => "User"
end

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

There's currently an owner_id field on the Group table, but I'm getting a PostgreSQL Error column users.group_id does not exist when I try and do anything involving group.owner . I'm fairly lost - any ideas on the best way to represent multiple associations to the same model here?

So I think I follow what you are trying to get at, this is a quick ERD created in Dia:

简单的

It looks like you just need to add the direct association for ownership between a User and a Group. I used the column owner_id so the table and model are more clear and avoid confusion about multiple user_id columns. Then the following models will work:

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
    belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"
end

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
    has_many :owned, :class_name => "Group", :foreign_key => "owner_id"
end

What about:

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users, :through => :membership
    has_one :owner, :class_name => "User"
end

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups, :through => :membership
    has_many :owned, :class_name => "Group"
end

And create model Membership with user_id and group_id ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM