I'm trying to get a user-interface going, where the user can choose which users he/she would like to add to a group. edit.html.erb for the Group displays a list of users currently assigned to the group we're editing, as well as a list of users not assigned to this group yet. On both lists there are buttons to assign a user to the group resp. to remove the user from the group. (see code below).
This works. Almost. There are some unexpected behaviours that puzzle me:
- the topmost row on both lists cannot be moved to the other list. When clicking the '>' or '<' button next to the topmost-listelement the application executes an "update" command instead of adding or removing the user via the action => command that is assigned to the button. (when I sort the users according to id intead of names, it is still the top-row that can't be moved with the buttons; it must have something to do with the position, I think)
- the update-button as well as the "show" and "back" links are being displayed at the very top, even though, in the code they follow after the lists... an indication that I'm doing something fundementally wrong, it seems to me.
can you get me back on track? Any comments and improvements are very welcome! thank you for your time haddock
ps I'm planning to use partials later on, but for the moment I would like to get this working first
---------------------------------------------------------views/groups/ edit.html.erb <h1>Editing group</h1>
<%= error_messages_for :group %>
<% form_for(@group) do |f| %> <p> <b>Name</b><br /> <%= f.text_field :name %> </p>
<p> <table> <tr> <th>Users of this group</th> <th></th> </tr>
<% for user in @users_of_group %> <tr> <td><%= button_to '>', :action => :remove_user_from_group, :user_id => user.id, :group_id => @group.id %></td> <td><%=h user.id %></td> <td><%=h user.name %></td> </tr> <% end %>
<table> <tr> <th>Users available</th> <th></th> </tr>
<% for user in @users_not_of_group %> <tr> <td><%= button_to '<', :action => :add_user_to_group, :user_id => user.id, :group_id => @group.id %></td> <td><%=h user.id %></td> <td><%=h user.name %></td> </tr> <% end %> </p>
<p> <%= f.submit "Update" %> </p> <% end %>
<%= link_to 'Show', @group %> | <%= link_to 'Back', groups_path %>
---------------------------------------------------------excerpt from groups_controller.rb # GET /groups/1/edit def edit @group = Group.find(params[:id]) @users_of_group = @group.users.find(:all, :order => "name") @users_not_of_group = User.find_by_sql(["select * from users where id not in (select user_id from groups_users where group_id = ?) order by name", params[:id]]) end
def add_user_to_group @user = User.find(params[:user_id]) @group = Group.find(params[:group_id]) @group.users << @user redirect_to :action => :index end
def remove_user_from_group @user = User.find(params[:user_id]) @group = Group.find(params[:group_id]) @group.users.delete(@user) redirect_to :action => :index end