← Back to Upcase

Replacing :onclick => remote_function for a check_box_tag in Rails 3.1


(Dean Richardson) #1

I’m still working on cleaning up failing tests in my Rails app now that I’ve upgraded it to Rails 3.1

I have a messaging functionality in my app that allows clients and providers to exchange private messages with each other regarding their projects.

In their inbox, users see a list of messages and a checkbox next to each one. If they check the checkbox, I have some js/ajax inline that marks the message for deletion and “puts” a messages#add_remove_message/id action:

<%= check_box_tag('id', 'id', false, :onclick => remote_function( :url => { :action => :add_remove_message, :id => message.id, :method => :put } )) %>

Of course, remote_function went away in Rails 3.1, and I should be replacing this code with some kind of unobtrusive javascript approach. Most of the tutorials explain that using :remote => true is the way to go in general to get rid of remote_function, perhaps with some data-href invocation as well. But that doesn’t seem to hold for check_box_tag.

What’s the best way to proceed here? I just want an ajax-y way to let users easily archive an inbox message without a page reload. It would be nice if I could keep the existing add_remove_message method but I’ll happily ditch it in favor of something else if it leads to a better overall solution.

The current add_remove_message method looks like this:

  def add_remove_message
    add_remove_ids = Array.new
    unless cookies[:add_remove].empty?
      add_remove_ids = cookies[:add_remove].split('|')
    end
    if add_remove_ids.include? params[:id]
      add_remove_ids.delete params[:id]
    else
      add_remove_ids << params[:id]
    end
    cookies[:add_remove] = add_remove_ids*'|'
    render :nothing => true
  end

This is legacy code from a previous freelance developer who worked on this messaging module. I’m not wedded to it (though it has the advantage that I understand what it does!)

I’d be grateful for suggestions on how to proceed, whether it involves a simple change in syntax, some jQuery plugin or a complete overhaul of the whole message deletion UI.

Thanks,

Dean Richardson
Genlighten.com