Update attribute on check box click (Rails 3)
I've been searching forever to find an actual answer to this:
What would be the best way to update an object's attribute via ajax when a checkbox is clicked? It's simply a matter of wanting to flip an attribute from false to true and vice versa.
There are one or two threads on stackoverflow about this, but they either empl开发者_如何学Coy observe_field (I'd rather just do it with a Prototype function) or have never solved the problem at all, it seems.
Again, this is Rails 3 and Prototype.
I guess it's the checkbox part that's tripping you up?
All you really need to do is have a method in your model to toggle the appropriate field
# somewhere in your model
my_boolean_field.toggle
and then bind a .click()
handler to your checkbox to do an ajax request. If you need to, in the .click()
handlers callback you can update the checkbox but I'm not sure if that's necessary.
The only part that's tricky here is what to do if the user clicks the checkbox quickly several times. One option is to disable the checkbox after it's clicked until the callback finishes.
精彩评论