Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 267
ark Avatar asked Dec 12 '22 04:12

ark


1 Answers

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

simple erd

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
like image 124
mguymon Avatar answered Jan 03 '23 23:01

mguymon