Saturday, February 12, 2011

Update row status using ajax

I am currently trying to program my first ajax interface using Rails.

The application currently shows a table populated with list items. The user has to approve or reject each of the list items. I currently have an edit link at the end of each row that shows a form in which I can approve the list item.

I am thinking on using a checkbox instead of the edit link. When the user clicks the checkbox I want to update the database with the status, user name and date/time without leaving this page.

  1. What steps should I follow?
  2. Can I use a checkbox or am I restricted to buttons?
  3. What xxx_remote helper should I use?
  4. How can I update the checkbox state with the results of the ajax call?
  • I don't think that a checkbox is the correct control for what you're looking for. You said you want user's to be able to approve or reject items which means that you have 3 states: unhandled, approved and rejected. A checkbox only supports 2 states: off and on

    I would use two links accept and reject and then do it as follows.

    In your view:

    ...
    <tr id="item1">
      <td>Accept or Reject</td>
      <td>
        link_to_remote 'accept', :action => :accept, :id => 1, :method => :post
        link_to_remote 'reject', :action => :reject, :id => 1, :method => :post
      </td>
    </tr>
    ...
    

    In your controller

    def accept
      item = Item.find(params[:id])
      item.accept
      respond_to do |want|
        want.js {
          render :update do |page|
            page << "$('item_#{item.id}').cells[0].innerHTML = 'Accepted'"
            ...include other updates you need to make to your row...
            page.visual_effect :highlight, "item_#{item.id}"
          end
        }
      end
    end    
    ... similar for reject method ...
    
    hectorsq : I have just updated my application. It worked fine!
    From Andrew
  • This is a comment to solution proposed by Andrew,

    I had to write params of link_to_remote function like this

    link_to_remote 'reject', :url => {:action => :reject, :id => item.id, :method => :post}
    

    Also, remember to add new actions to your routes.rb if You are using restful resources i.e.

    map.resources :items, :member => {:accept => :post, :reject => :post}
    
    hectorsq : Thanks for your answer. I added the new actions too.

0 comments:

Post a Comment