Reputation: 417
I'm trying to make a page that updates my users' roles. I have a users controller and a method/action in the controller called "admin". All the admin definition does is store all the users in @users. In routes, the resource is users, and it has a collection do that gets :admin.
I'm updating the roles by creating a new form for each user and I have a save button for each form next to each user.
<table>
<tr>
<th>Username</th>
<th>Role</th>
<th>Update</th>
</tr>
<% @users.each do |user| %>
<%= form_for [user], :user => { :action => "update" } do |f| %>
<tr>
<td><%= user.username %></td>
<td><%= select("user", "role", options_for_select(['member', 'moderator','admin'], user.role) )%></td>
<td><%= f.submit %> </td>
</tr>
<% end %>
<% end %>
</table>
This works and updates, but it's not very intuitive. I would like to either have the submit button after the whole thing, or an ajax call that updates the role on change so the user doesn't have to worry about clicking 'save' at all.
Is there a way to avoid the double nested loop, and possibly add an ajax where the update button isn't necessary?
Thanks for any advice or help.
Upvotes: 0
Views: 365
Reputation: 2254
The first thing you can do is change your forms to be remote forms that use ajax to update. You can do this in rails with one change
<%= form_for [user], :user => { :action => "update" }, :remote=>true do |f| %>
The effect here will be that the submit button for each user submits the form change without taking you off the page.
Next if you want to remove the submit buttons entirely and have it submit on change, you can use some very simple jQuery that listens for changes on input fields and submits the parent form when a change occurs. Here is an article to get you started on that
Making one submit button for all the objects is probably more difficult. From what I know you'd have to print the fields for all the objects into a single form, probably send the form to a different action, and then cycle through all the users that have changes in the form and call the update action on them separately. There may be an easier way, though.
Upvotes: 2
Reputation: 1430
So, if you'd like to go the AJAX route, I'd recommend bringing in a JavaScript library like jQuery (probably not ExtJS if you're using a good bit of HTML).
JQuery has built in AJAX functionality.
Upvotes: 1