#52
Jul 02
Update through Checkboxes
See how to select multiple items using checkboxes and perform an action on the selected items in this episode.
Resources
# routes.rb map.resources :tasks, :collection => { :complete => :put } # tasks_controller.rb def complete Task.update_all(["completed_at=?", Time.now], :id => params[:task_ids]) end
<% form_tag complete_tasks_path, :method => :put do %> <ul> <% for task in @incomplete_tasks %> <li> <%= check_box_tag "task_ids[]", task.id %> <%= task.name %> </li> <% end %> </ul> <%= submit_tag "Mark as Complete" %> <% end %>




let me see
Another great railscast as usual. One thing that I'd like to know is if there's a way to make the checkboxes each have a different ID in the HTML code, and still have the form work?
I noticed in the example that every checkbox has the same ID, which is invalid, as ID's are meant to be unique within a XHTML document.
Thanks again Ryan for you great work.
@Leeky - It is actually the 'name' of the field that is referenced (and not the id) for submission. It is common practice (as many rails helpers do) to call the id and name the same. Im sure you can used the name as described in this screencast and use the dom_id plugin (http://topfunky.net/svn/plugins/dom_id/) to give your forms unique ids. This would be helpful for validation and for giving this task ajaxy goodness.
Great job Ryan. One thing your code snippet has "form_for" not "form_tag".
If we were to do this with multiple users, how can we first ensure that the task IDs belong to the current logged in user (in case someone edits the HTML and puts in a task ID that doesn't belong to them)?
@Rob
current_user.tasks.update_all(["completed_at=?", Time.now], :id => params[:task_ids])
end
Sorry two other things:
- submit_tag needs a closing %>
- it's ":collection" not ":collections"
:)
@JackVandaL, thanks, fixed. I gotta learn to copy and paste the code instead of retyping it. :/
Ryan,
Great episode. I have question concerning the controller. I see the pattern of always having a new -> create, edit -> update method.. But then I see some repeated code in the new and the create (like typically find the object by ID). Could use call the new method to do the setup of the default data and override them from the create method? Or is there a better way to refactor that?
This was great. Just wondering if there is a way to do this without using REST?
My app is not as clean as this one at this point and I am lost when it comes to getting the "collection" of data passed to the controller method.
I have a question. In this example the items disappear from the list when they are marked as complete.
What if you want to display the complete list all the time, but the check_box default value is based on the values from the tasks.