check_box绑定到第一个元素

时间:2018-04-06 15:08:07

标签: ruby-on-rails checkbox

我需要在模型中更新值isCompleted。但我的代码仅适用于id = 1的todo项目。如果我点击todo项目ID的另一个复选框保持不变(id = 1)。如何将我的复选框连接到其他项目。

class TodosController < ApplicationController
  def create
    @todo = Todo.create(todo_params)
    if @todo.save
      redirect_to root_path
    else

    end
  end

  def update
    @todos = Todo.find_by(params.require(:todos).permit(:id))
    @todoo = @todos.update(bool)
    redirect_to root_path
  end

private
  def todo_params
    params.require(:todo).permit(:text, :project_id) # add any other attributes you want
  end

  def bool
    params.require(:todos).permit(:isCompleted)
  end
end

index.html.erb

<% @projects.each do |project| %>
    <div class="col-md-6 col-lg-4">
       <div class="todo">
           <table>
               <tr class="border_bottom">
                  <td>
                    <h2><%= project.title %></h2>
                  </td>
                </tr>
                <tr>
                  <td>  
                    <ul>
                      <% project.todos.all.each do |todo| %>
                        <li>
                          <%= form_for :todos, :url => todos_update_path, method: :patch, html: {id: "update" } do |f| %>
                            <p>
                              <%=f.check_box(:isCompleted,{class: 'icheckbox_square-blue', checked: todo.isCompleted},todo.id) %> 
                              <%= todo.text %>
                              <%= f.hidden_field :id, :value => todo.id %>
                            </p>
                          <% end %>
                         </li>
                       <% end %>
                     </ul>
                   </td>
              </tr>
       </table>
     </div>
   </div>              
<% end %>

的application.js

 $(".icheckbox_square-blue").change( function(){
    $('#update').submit();

1 个答案:

答案 0 :(得分:1)

您需要使用嵌套表单。你有2个对象

Project has_many :todos

然后您需要构建表单form_for @project

查询todos

中的projects#new

显示所有todos个孩子,f.fields_for :todos

了解更多信息

http://guides.rubyonrails.org/form_helpers.html#nested-forms