通过javascript发送Rails PUT请求

时间:2011-01-01 02:47:04

标签: javascript controller ruby-on-rails-3 action put

如何在Rails中通过javascript向动作发送PUT请求?以下是我在.html.erb文件中的操作方法:

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

我如何在javascript中执行此操作?

1 个答案:

答案 0 :(得分:1)

添加:remote => true以在链接上启用ajax。

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

假设您需要index页面中的检查任务。

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>