使用 Rails 中的 Cocoon gem 通过嵌套属性更新关联模型上的多个复选框

2023-11-29

我找到了这个答案here这应该能够解决我的问题,但事实证明答案是一对多关联。顺便说一句,我正在使用 Rails 5.2

在我的多对多中,我有一个任务模型 has_manytest_methods通过tasks_test_methods where tasks_test_methods是一个连接表。

class Task < ApplicationRecord
  has_many :tasks_test_methods, inverse_of: :task, :dependent => :destroy 
  has_many :test_methods, :through => :tasks_test_methods

  accepts_nested_attributes_for :tasks_test_methods, reject_if: :all_blank, allow_destroy: true
end

这是我的连接表模型tasks_test_methods

class TasksTestMethod < ApplicationRecord 
  belongs_to :task
  belongs_to :test_method

  accepts_nested_attributes_for :test_method, :reject_if => :all_blank
end

和我的 TestMethod 模型

class TestMethod < ApplicationRecord
  has_many :tasks_test_methods, inverse_of: :test_method, :dependent => :destroy 
  has_many :tasks, :through => :tasks_test_methods
end

我的 TasksTestMethods 表很简单,只接收task_id and test_method_id

create_table "tasks_test_methods", id: false, force: :cascade do |t|
    t.bigint "task_id", null: false
    t.bigint "test_method_id", null: false
end

我有一个预定义的列表test_methods显示并需要添加到task创建时。例如。

<TestMethod id: 1, name: "Visual Testing (VT)", code: nil, description: nil, category_id: 1, created_at: "2018-05-15 12:11:38", updated_at: "2018-05-15 12:11:38">

I want to have all these test_methods in the new task form like this enter image description here

因此,当用户选中带有标签的复选框时Visual Testing一条新记录的创建方式如下(rails 控制台的示例):

2.5.1 :176 > params = { task: { name: "Test", client_id: 1, tasks_test_methods_attributes: [test_method_id: 1]}}
 => {:task=>{:name=>"Test", :client_id=>1, :tasks_test_methods_attributes=>[{:test_method_id=>1}]}}
2.5.1 :177 > task = Task.create!(params[:task])
<ActiveRecord::Associations::CollectionProxy [#<TasksTestMethod task_id: 16, test_method_id: 2>]>

这是我的新task形式,这里我使用的是已经在fields_for part

= form_with(model: @task) do |f|
  .form-group
     %label Client Name:
        = f.select(:client_id, @clients.collect { |client| [ client.name, client.id ] }, { include_blank: "Select Client" }, { :class => 'form-control select2', style: 'width: 100%;' })
   .col-md-12
      = f.fields_for :tasks_test_method do |task_test_method|
        = render 'test_method_fields', f: task_test_method

并且在test_method_fields部分我有这个:

= collection_check_boxes :tasks_test_method, :test_method_ids, @test_methods, :id, :name do |box| 
  .form-group.row 
    .form-check.col-md-3
      = box.check_box
      %span.ml-2 
        = box.label

上面的代码按预期显示了复选框,但没有按预期工作。有人可以指导我如何进行这项工作吗?

我也将这些列入了白名单TasksController

tasks_test_methods_attributes: [:id, test_method_ids: []])

这是为浏览器控制台中的每个复选框生成的代码形式

<div class="form-check col-md-3">
  <input type="checkbox" value="1" name="tasks_test_method[test_method_ids][]" id="tasks_test_method_test_method_ids_1">
  <span class="ml-2">
   <label for="tasks_test_method_test_method_ids_1">Visual Testing (VT)</label>
  </span>
</div>

问题是我无法得到tasks_test_methods_attributes进入参数,当我点击其中的 2 个时test_methods并尝试添加一个任务,例如,我在控制台中得到这个:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"cuEnQNeh4iT+38AwsNduQGce5kxFcS7sFw0SAgpdvxJjVziFTnrSgzdq6LODNDxzhan2ne31YMeCcJdYL8VoSQ==", "task"=>{"client_id"=>"", "name"=>"", "department_id"=>"", "start_date"=>"", "offshore_flag"=>"0", "order_number"=>"", "description"=>"", "task_manager_id"=>"", "language_id"=>"", "client_ref"=>"", "testsite"=>"", "contact_person_phone"=>"", "contact_person"=>"", "contact_person_email"=>"", "information_to_operator"=>""}, "tasks_test_method"=>{"test_method_ids"=>["", "1", "2"]}, "commit"=>"Create Task"} 

当我尝试创建一个Task,它已创建但没有tasks_test_methods_attributes参数中的一部分。

这是我的TasksController new action

def new
  @task = Task.new 
  TestMethod.all.each do |test_method|
    @task.tasks_test_methods.build(test_method_id: test_method.id)
  end
 end

终于得到了这个任务的答案。我的整个方法是错误的,试图直接插入到连接表中(这是永远行不通的!)。

本文在阅读了多次之后,帮助我找出了我的错误。经过大约 3 天的时间寻找解决方案后,最终在 3 分钟内解决了问题。

在您的模型中,接受连接表的嵌套属性,如下所示:

accepts_nested_attributes_for :tasks_test_methods, reject_if: :all_blank, allow_destroy: true

在阅读时茧宝石文档,我发现这个说法很有道理。When saving nested items, theoretically the parent is not yet saved on validation, so rails needs help to know the link between relations. There are two ways: either declare the belongs_to as optional: false, but the cleanest way is to specify the inverse_of: on the has_many. That is why we write : has_many :tasks, inverse_of: :test_method

现在在我的Task模型,我有

has_many :tasks_test_methods, inverse_of: :task, :dependent => :destroy 
has_many :test_methods, :through => :tasks_test_methods

也在我的TestMethod模型,我有

has_many :tasks_test_methods, inverse_of: :test_method, :dependent => :destroy 
has_many :tasks, :through => :tasks_test_methods

然后在TasksController我将其添加到参数中,test_method_ids: []

最后我的形式是这样的:

.form-group
   = f.collection_check_boxes :test_method_ids, @test_methods, :id, :name do |test_method|
      .form-check.mb-4
         = test_method.check_box(class: "form-check-input")
         %label.form-check-label 
            %span.ml-2  
              = test_method.label

现在您的 HTML 元素应该如下所示:

<div class="form-check mb-4">
  <input class="form-check-input" type="checkbox" value="1" name="task[test_method_ids][]" id="task_test_method_ids_1">
  <label class="form-check-label">
   <span class="ml-2">
     <label for="task_test_method_ids_1">Visual Testing (VT)</label>
   </span>
  </label>
</div>

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Rails 中的 Cocoon gem 通过嵌套属性更新关联模型上的多个复选框 的相关文章

  • HABTM 关系和accepts_nested_attributes_for

    我有一个可以让我创建的表单新博客文章我希望能够创造新类别来自同一个表格 我在帖子和类别之间有一个习惯关系 这就是我遇到麻烦的原因 我有以下2个型号 class Post lt ActiveRecord Base has and belong
  • 在 Rails 中禁用连接池以使用 PgBouncer

    我们有一个 Ruby on Rails 4 2 8 项目 可以访问大型 PostgreSQL 数据库 我们将使用 PgBouncer 添加一个新的连接池服务器 由于 PgBouncer 将处理数据库连接池 我们是否需要关闭 Rails 自动
  • kaminari ajax 分页不更新分页

    我正在使用 kaminari gem 在 Rails3 中实现分页 我一直在关注github上的这段代码https github com amatsuda kaminari example commits ajax https github
  • Ruby 可选参数和多个参数

    我试图将方法的第一个参数设置为可选 后跟任意数量的参数 例如 def dothis value 0 args 我遇到的问题是 这似乎实际上不可能 当我打电话时dothis hey how are you good 我希望它将值设置为默认值
  • 在特定页面上执行 javascript 的正确“Rails”方式

    我试图在特定页面上运行 javascript 而我唯一的解决方案似乎是反模式 我有controller js内部生成的assets javascripts 我在用着gem jquery turbolinks 我的代码类似于以下内容 docu
  • 回滚后是否应该删除迁移

    我对 ruby 和 Rails 相当陌生 刚刚开始了解迁移 我的问题是回滚后删除迁移的最佳实践或正确时间是什么 到目前为止 我读到的内容是回滚后是否删除迁移的观点问题 但是在团队中工作时删除迁移是否有任何重大影响 以及保留迁移文件相对于删除
  • 如何在服务调用后检查 rspec 中的数组更改?

    目标很简单 例如我们有一个数组 name ghost state rejected name donkey state rejected 运行服务调用后UpdateAllUsers 这会将所有用户更改为 accepted name ghos
  • 通过 ESI:include 设置 Cookie,如何?

    我正在尝试使用 esi 在我的网站上创建忍者缓存 这个想法是 该网站大部分是静态的 我只需要在用户是否登录时做一些花哨的事情 所以我试图在页面A上放置一个 并在页面B的应用程序中设置触发器 这样我就可以将页面 A 缓存在 varnish 上
  • Rails 4 的 mobile_fu

    我正在尝试将我的应用程序从 Rails 3 2 13 切换到 Rails 4 在此过程中 我遇到了一个主要障碍 我使用 gem mobile fu 来确定用户是否来自移动设备 该 gem 需要 Railties 3 2 13 但 Rails
  • Rails 从 OrdersController 更新用户模型的属性

    这是我的代码 订单控制器类 def create order Order new params order if order purchase work GATEWAY store credit card options result wo
  • Capybara-webkit 无法处理与 bootstrap glyphicon 的链接

    我有一个链接 link to q span class glyphicon glyphicon trash span html safe feed item data confirm Are you sure toggle tooltip
  • Omniauth + Google + Faraday + 代理背后=如何设置代理?

    我的生产服务器是乌班图12 我在用着设计 OmniAuth处理 Google 身份验证 但是当 Google 将控件返回给我的应用程序时 我收到错误 网络不可达 我认为这是因为服务器位于代理后面 这是错误描述 Request URL htt
  • 如何使用 Ruby on Rails 3 检查 HTTP 请求的“Content-Length”字段?

    我正在使用 Ruby on Rails 3 在我的视图文件中我有以下代码 为了避免服务器过载 我会在服务器接收上传文件之前检查上传文件的大小 这是因为 按下表单的提交按钮 服务器会先完整接收文件 然后再检查文件 我知道一个HTTP 请求有标
  • 使用redirect_to :create 动作

    我正在尝试重定向到另一个控制器的创建方法 但是 我找不到将方法设置为 POST 的方法 这将导致调用索引方法 使用 method gt post只是创建一个新参数 但不会更改 http 方法 有什么想法如何重定向到创建方法吗 您无法在重定向
  • Emacs、ruby:将 do 结束块转换为大括号,反之亦然

    我经常发现自己转换这样的代码 before do something end to before something 有没有办法在 emacs 中自动执行此任务 我使用 ruby mode 和 rinary 但它们在这里没有太大帮助 rub
  • 创建一个默认为零的工厂关联?

    在factories rb 文件中使用FactoryGirl gem 如何创建一个关联默认为nil 的工厂 我正在思考以下几点 Factory define user do factory factory association post
  • 有没有办法使用 Rspec/Capybara/Selenium 将 javascript console.errors 打印到终端?

    当我运行 rspec 时 是否可以让 capybara selenium 向 rspec 报告任何 javascript console errors 和其他异常 我有一大堆测试失败 但当我手动测试它时 我的应用程序正在运行 如果不知道仅在
  • 如何以 Rails 形式将图像从 上传到具有 Rails Active Storage 的 S3?

    正如标题中所述 我正在尝试使用 Rails 的 Active Storage 从嵌套在 Rails 表单中的元素将图像上传到我的 S3 存储桶 到目前为止我已经能够使用使用 Active Storage 上传图像 这User class h
  • Rails 3 SSL 路由从 https 重定向到 http

    这个问题与此相关SO 问答 rails 3 ssl deprecation https stackoverflow com questions 3634100 rails 3 ssl deprecation建议使用routes rb和类似的
  • 用于验证目的的动态查找方法

    我正在使用 Ruby on Rails 3 0 7 我想在运行时查找一些记录以进行验证 但为该查找方法传递 设置一个值 也就是说 在我的班级中 我有以下内容 class Group lt lt ActiveRecord Base valid

随机推荐