【问题标题】:check_box tied to the first elementcheck_box 绑定到第一个元素
【发布时间】:2018-04-07 02:45:49
【问题描述】:

我需要更新模型中的 isCompleted 值。但我的代码仅适用于 id=1 的待办事项。如果我单击另一个待办事项 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 %>

应用程序.js

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

【问题讨论】:

    标签: ruby-on-rails checkbox


    【解决方案1】:

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

    Project has_many :todos

    然后你需要构建一个表单,form_for @project

    projects#new 中查询todos

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

    阅读更多

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多