Rails check_box_tag如何在ajaxily中检查时传递值

Cat*_*ish 4 ruby ajax ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

在我的任务模型的索引页面上,我想为每个行显示一个复选框,该行对应于我的任务数据库表中的布尔字段"完成".

目前我的代码进入方法"完成",但它不包含用户刚刚执行的复选框的值(即,如果他们只是选中了框,则它不会传递给我的"完整"方法).

我如何传递用户刚刚执行的值 - 是选中还是未选中?

/views/tasks/index.html.erb

<% @tasks.each_with_index do |task, i| %>
    <tr>
        <td><%= check_box_tag 'Complete', task.complete, task.complete, :data => {:remote => true, :url => url_for( :action => 'complete', :id => task.id, :complete => task.complete ), :method => :put}, :class => 'input-large' %></td>
    </tr>
<% end %>
Run Code Online (Sandbox Code Playgroud)

器/控制器/ tasks_controller#完整

# PUT /complete/1
  def complete
    @task = Task.find(params[:id])
    p "inside complete"
    p "complete = #{params[:complete]}"
    @task.complete = 

      if @task.update_attributes(params[:task])
        p "inside update"
        render :text => "success" 
      else
        p "inside error"
      end

  end
Run Code Online (Sandbox Code Playgroud)

nat*_*tes 7

rails/jquery-ujs github repo中这个问题的建议对我有用:https://github.com/rails/jquery-ujs/issues/440#issuecomment-197029277

对你来说它将是:

<%= check_box_tag 'complete', '1', task.complete, {
  onchange: "$(this).data('params', 'complete=' + this.checked)",
  data: { url: url_for(action: 'complete', id: task.id,), remote: true, method: :patch },
} %>
Run Code Online (Sandbox Code Playgroud)


Sri*_*eva 5

如果你使用 jQuery,你可以编写一个点击事件。

$('.input-large').click(function() {
  var checked; 
  if ($(this).is(':checked')) {
    checked = true;
  } else {
    checked = false;
  } 
  $.ajax({
      type: "POST",
      url: "/tasks/complete",
      data: { id: $(this).data('post-id'), checked: checked }
   });     
});
Run Code Online (Sandbox Code Playgroud)