NoobOnRails

Ruby on Rails tips, tricks and hints for the aspiring rails hero.



Sunday, September 24, 2006

How to make a Dynamic Sortable List


This one was a but tricky for my noobish rails mind but once I found the solution, it made a lot of sense. Basically, I had this list of items that I needed to be sortable. The problem was, the use could change the contents of this list via an RJS-friendly selection list. When the user did make a change, the list wouldn't be sortable anymore. Why wasn't it sortable anymore you ask? Because my rjs template was only replacing the list container, to showcase the new contents, and not the actual JavaScript that rendered the list sortable. Here's what my selection list looked like:

<%= form_remote_tag :url => {:action => "get_list", :id => @days_out},
:html => {:id => "shopping_list"} %>
<%= select("dinner", "days_out", %w{1 2 3 4 5 6 7}, { :include_blank => true })%>
<%= submit_tag "Get List" %>
<%= end_form_tag %>


and my shopping list container looked like this:




and here's the scriptaculous code that makes my list sortable:

<%= render :partial => 'sort'%>


(the sort partial):

<%= sortable_element 'shop_list', :complete => visual_effect(:highlight, 'shop_list'), :url => { :action => "order" } %>

So I had my selection list form, my list of sortable items and the code to make my list sortable. What does the dynamic updating? Why my RJS template of course. Here's the get_list action in my controller:
def get_list @days_out = params[:dinner][:days_out] @recipes = Dinner.find(:all, :conditions => ["dinner_night between ? and ?", Date.today, Date.today+(@days_out.to_i)], :include => :recipe).map {|r| r.recipe.ingredients} Dinner.parse(@recipes) end

I grab the values that were passed by the form and stick them into the @days_out instance variable. Then I use that value to determine which ingredients I need to populate my selection list with. That "Dinner.parse(@recipes)" just cleans up the ingredients so the user gets a basic list, uncluttered by the (what I've deemed) unnecessary.

Here's the get_list.rjs template:

page.replace_html 'shop_list', :partial => 'item' page.replace_html 'sort', :partial => 'sort' page.visual_effect :highlight, 'shop_list', :duration => 1

As you can see in the rjs template, I first replace the shopping list partial, then I replace the scriptaculous code and then I wrap it up by yellow-fading the whole list. Purty ain't it?

1 Comments:

  • At 4:00 AM, Anonymous Anonymous said…

    Can't see any list.
    Using IE 7 and Opera 9 on win xp

     

Post a Comment

<< Home