Multiple associations with one table
I've searched a bit before asking this but I definitely can't get it working...
I've got a Group model which has a manager_id, a designer_id and other user ids corresponding to different user roles in this group. They are has_one User associations in the Group model with different foreign keys.
I've tried mul开发者_开发知识库tiple belongs_to associations in the User model but... a User which belong to the group (they have a group_id column) can be one of these roles and I realy don't know how to check these and how to do the associations in the User model.
Thank you in advance.
PS: The users can just belong to one group, that's why I've simply put the group_id in the User model and not on a join table.
If being a manager or a designer in a group means that someone is a member if that group, there's no way you can do this easily, you should create a membership model, that has a "role" property that says which role the user represents in a specific group, here's how it would look like:
class User
has_one :membership
end
class Group
has_many :memberships
end
class Membership
belongs_to :group
belongs_to :user
validates_presence_of :role
validates_inclusion_of :role, :in => [ 'manager', 'designer', 'member' ]
validates_uniqueness_of :user_id, :scope => :group_id
end
This gives you the functionality and even allow you to define as many roles for your groups as possible.
belongs_to
is more powerful than you might imagine
For example, to create a belongs_to association about Managers, on the User
In your User class:
belongs_to :manager, :primary_key => :manager_id, :class_name => "User"
Which will do the query, querying where the manager_id
field in the User(s) table matches the manager_id
in the Group(s) table.
Or, if the column in the user table is not called "manager_id":
belongs_to :manager, :foreign_key => :my_manager_id, :primary_key => :manager_id
Which will match the my_manager_id
column in the User(s) table to the manager_id
column in the Group(s) table.
Then you should be able to do:
user.manager.exists?
and what-have-you
Edit: It's also possible I'm not quite understanding your data model, but I think this approach may also work with a has_one :manager, :through => :group
situation. has_one :manager, :through => :group
, for example. Except :foreign_key
and class_name
doesn't work in these situations, per the documentation for has_on
, because "Options for :class_name and :foreign_key are ignored, as the association uses the source reflection".
精彩评论