سؤال

How would I go about sending a PUT request to an action through javascript in Rails? Here's how I do it in the .html.erb file:

<%= link_to "Check", check_task_path(task), :method => :put %>

How would I do this in javascript?

هل كانت مفيدة؟

المحلول

Add :remote => true to enable ajax on the link.

<%= link_to "Check", check_task_path(task), :method => :put, :remote => true %>

Assuming you want a check tasks in index page.

index.html.erb

<table>
  <tr>
    <th>Name</th>
    <th>Completed</th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @tasks.each do |task| %>
  <tr>
    <td><%= task.name %></td>
    <td id="completed_<%= task.id %>"><%= task.completed %></td>
    <td><%= link_to 'Show', task %></td>
    <td><%= link_to 'Edit', edit_task_path(task) %></td>
    <td><%= link_to 'Destroy', task, :confirm => 'Are you sure?', 
            :method => :delete %></td>
    <td><%= link_to "Check", check_task_path(task), :method => :put, 
            :remote => true, :class => :check_task %></td>
  </tr>
<% end %>
</table>

tasks_controller.rb

  def check
    @task = Task.find(params[:id])
    @task.completed = true
    respond_to do |format|
      if @task.update_attributes(params[:task])
        format.html { redirect_to(@task, 
         :notice => 'Task was successfully updated.') }
        format.xml  { head :ok }
        format.js  
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @task.errors, 
           :status => :unprocessable_entity }
        format.js
      end
    end

check.erb.js

<% if @task.errors.empty? %>
  jQuery("#completed_<%= @task.id %>").html("true.");    
<% else %>
  alert("Task could not be saved.");
<% end %>

routes.rb

  resources :tasks do
    member do
      put 'check'
    end
  end

application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Tada</title>
  <%= stylesheet_link_tag :all %>
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" %>
  <%= javascript_include_tag :defaults %>

  <%= csrf_meta_tag %>

</head>
<body>

<%= yield %>

</body>
</html>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top