Luis Novo
Luis Novo

Reputation: 640

ActionController::RoutingError: No route matches -> while using checkbox + ajax

I am building a simple task management app and a weird problem happens when I try to handle checkbox to indicate a task is done.

Here is code I came up with:

<%= check_box_tag "id", "id", task.done, 
    :onclick => remote_function(
      :update => "task", 
      :url => { :action => :update, :controller => :tasks, :id => task.id }, 
      :with => "'task[done]=true'", 
      :complete => "alert('hi')"  ) %>

It does print the checkbox, and it does check it automatically depending on the status of task.done. But when I fire the onclick and watch the logs, I see the following entry:

Started POST "/tasks/20" for 127.0.0.1 at 2011-04-25 23:15:44 -0300 ActionController::RoutingError (No route matches "/tasks/20"):

Looking at my config/routes.rb file, I have:

 resources :tasks

Can you help me figure out what I am doing wrong? Why is the route not found?

Here is the full code for the _task.html.erb view.

<tr>
  <td class="task">
    <span class="tasktitle">


<%= check_box_tag "id", "id", task.done, 
    :onclick => remote_function(
      :update => "task", 
      :url => { :action => :update, :controller => :tasks, :id => task.id }, 
      :with => "task[done]=true", 
      :complete => "alert('hi')"  ) %>



<span class="<%= if (task.done) then "editable_field_complete" else "editable_field" end %>" id="task_title_<%= task.id %>">
<%= best_in_place task, :title, :type => :input %>
</span>
</span>
    <span class="taskdelete"><%= link_to "delete", task, :method => :delete, :class => "delete",
                                     :confirm => "You sure?",
                                     :title => task.title %></span>
    <span class="taskcreated">
      Created <%= time_ago_in_words(task.created_at) %> ago.
    </span>
  </td>
</tr>

Thanks a lot guys

Upvotes: 2

Views: 3485

Answers (1)

DanneManne
DanneManne

Reputation: 21180

The problem seems to be that the remote_function submits the data with the POST protocol but when you use resources in routes.rb then it only accept the PUT protocol when calling the update action.

Try adding the following parameter to your remote_function:

:method=>:put

So the end result will be:

<%= check_box_tag "id", "id", task.done, 
    :onclick => remote_function(
    :update => "task", 
    :url => { :action => :update, :controller => :tasks, :id => task.id }, 
    :method => :put,
    :with => "task[done]=true", 
    :complete => "alert('hi')"  ) %>

Upvotes: 3

Related Questions