On 4/29/05, Richard Livsey
<richard-gfRugNUWsoQdnm+yROfE0A@public.gmane.org>
wrote:> I''m working on a few test apps to get to grips with RoR and am
wondering
> what the best way to build a few models.
>
> In this app, there are users and groups.
> A user can be a member of many groups, and a group has an owner - which
> is a user.
>
> So here we have 2 associations between these tables - group members, and
> group owners.
>
> I will have a ''users'' table, a ''groups''
table. Then a ''groups_users''
> table to store the linkages for group members. But the problem then is
> then the group owners. I could have this as a column in groups_users
> (is_owner or somesuch), but this implies that an owner is a type of
> member, which they aren''t really, they are just a property of the
group.
>
> So the way would be to have an ''user_id'' field on the
groups table which
> contains the owner user ID for a belongs_to/has_one association.
>
> Ideally I''d rename this so that I could call it
''owner_id'' in the table
> and access it as group.owner as opposed to group.user.
>
> I guess my question is, does it look like this is the way to go about
> it? And are there any gotchas with having multiple associations across
> the same tables which I should be aware of.
>
> The easiest way is to try it out for myself, which I will be doing soon
> but I''m building other parts of the app before I get to this bit.
>
> Thanks in advance!
>
> --
> R.Livsey
> www.livsey.org
>
> _______________________________________________
> Rails mailing list
> Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
You''ve got the idea. Rails gives you the ability to call the column
whatever you want.
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
belongs_to :owner, :class_name => ''User'', :foreign_key
=> ''owner_id''
end
create table users (
id ...
)
create table groups (
id ...
owner_id ...
)
create table groups_users (
group_id ...
user_id ...
)
This will give you access to group.owner
Jason