Search code examples
ruby-on-railsrubyruby-on-rails-3rubygemsacts-as-list

Create a custom move_up route and move_down actions/route Rails


I am trying to create two little buttons with an up and down arrow, and sort my Products based on that. I have a model called Product, and am using acts_as_list to keep track of position.

Do I do something like this in my controller to create the routes?

resources :products
post "products/move_up"
post "products/move_down"

and in my products controller

def move_up
  @product.find(params[:id])
  @product.move_higher
end

def move_down
  @product.find(params[:id])
  @product.move_lower
end

and in my view

<%= link_to "UP", products_move_up_path(product) %>
<%= link_to "Down", products_move_down_path(product) %>

But I'm not doing something right. I keep getting the error

Couldn't find Product with id=move_up

Can anyone help me create this route relationship?

EDIT: Now I am getting the error

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.find

Here is some more code

View Code

<ul>
<% item.children.each do |child| %>
<li id='category_<%=child.id %>'>
  <span><%= child.name %></span>

  <% child.products.position.each do |product| %>
    <br /><%= link_to "UP", move_up_product_path(product), method: :put %> | 
    <%= link_to "Down", move_down_product_path(product), method: :put %> ----------<%= product.position %> 
   <%= product.name %>
    <%= link_to 'Edit', edit_product_path(product) %>
    <%= link_to 'Delete', product, :method => :delete, :confirm => "Are you sure you want to delete this product?" %> <br />

    <% end %> 
  <%= render 'shared/children', :item => child unless child.leaf? %>
  </li>
 <% end %> <br />
 </ul>

The code it seems to be hanging up on is here

 def move_up
   #Need to add a before filter to find product so I don't have to keep doing it.
   @product.find(params[:product])
   @product.move_higher
 end

When it executes the find. Thanks!


Solution

  • So 'Up' and 'Down' are really more of an update, so you'd want to use 'PUT', but also, your not defining your routes correctly. Try this:

    resources :products do 
      member do
        put :move_up
        put :move_down
      end
    end
    

    Which should create the routes that you are looking for.

    Also, your links need to perform a :put, instead of a :get which is the default action for a link. Try this:

    <%= link_to "UP", move_up_product_path(product), method: :put %>
    

    That should work for you, to check your routes you can always run rake routes

    Hope this helps, just accept/up vote if it does!

    Joe