Relationship modeling and routing
Consider these two resources: user and group.
Rules:
- A group is owned by an user;
- A group contains many users;
- A user can have many groups;
- A user can attend to many groups;
What I have:
class User
has_many :groups, :foreign_key => "owner_id"
has_and_belongs_to_many :attended_groups,
:class_name => "Group",
:join_table => "groups_members",
:foreign_key => "member_id"
end
class Group
belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"
has_and_belongs_to_many :members, :class_name => "User",
:join_table => "groups_members",
:association_foreign_key => "member_id"
end
My que开发者_StackOverflow社区stion is: what is the best (elegant?) solution to add actions in group controller, and also routes to, while owner sees his group (and all members), let it see who is not there and maybe add it. Something like: /groups/1/add_member/2. Same thing for a user to add a group, while he sees its page.
I've managed to make it work, but I would like to see how it should be. The problem is too simple to have a solution that complicated as mine. Maybe the way I modeled the problem is not the best way too.
Just for the record, I'm a completely newbie to Rails.
Please comment! And thanks in advance!
You probably want to do a nested resource pattern. It adheres to REST though, so you're going to have to deal with the naming conventions for urls.
resources :groups do
resources :users
end
This is a good resource: http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default
In order to add an existing user to an existing group I would probably define a new route.
match '/groups/:group/users/add' => 'groups#add'
And this in the controller
@group = Group.find params[:group]
@user = User.find params[:user]
@group.users << @user if @user
精彩评论