保存时Rails grouped_collection_select不起作用

时间:2018-09-28 06:20:47

标签: ruby-on-rails ruby-on-rails-5

我正在使用grouped_collection_select过滤掉Rails 5格式的关联信息。

第一个grouped_collection_select属性一起使用,以过滤出与合作伙伴相关的数据。但是,第二个grouped_collection_select在过滤与属性相关联的字段时确实起作用,但是在尝试保存时出现错误:

1 error prohibited this trial from being saved:

Field must exist

表格

<%= form_with(model: trial, local: true) do |f| %>
 <label>Co-operator</label>
 <%= f.collection_select :cooperator_id, Cooperator.order('last_name'), :id, :full_name %>
 <label>Property</label>
 <%= f.grouped_collection_select :property_id, Cooperator.order('last_name'), :properties, :full_name, :cooperator_id, :name %>
 <label>Field</label>
 <%= f.grouped_collection_select :field_id, Property.order('name'), :fields, :name, :property_id, :field_name %>
 <%= f.submit 'Submit' %>
<% end %>

当我将grouped_collection_select更改为collection_select时,它可以正常工作。但是,这不适合我的需求。

<%= f.collection_select :field_id, Field.all, :id, :field_name %>

试用版控制器

def trial_params
 params.require(:trial).permit(:cooperator_id, :field_id, :property_id)
end

试用模型

class Trial < ApplicationRecord
  belongs_to :cooperator
  belongs_to :property
  belongs_to :field
end

登录

Processing by TrialsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"THfy+JGBYbNvzurUscPfP8LQbnnvIz1HBEfeFRiZrocXtiu4ayncEA8cNBA2IkPgcphLoa0QWsEueFBEP29OXA==", "trial"=>{"cooperator_id"=>"2", "property_id"=>"2", "field_id"=>""}, "commit"=>"Create trial", "id"=>"11"}
Cooperator Load (0.5ms)  SELECT  "cooperators".* FROM "cooperators" WHERE "cooperators"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/trials_controller.rb:49
  Property Load (0.4ms)  SELECT  "properties".* FROM "properties" WHERE "properties"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/trials_controller.rb:49
Field Load (0.4ms)  SELECT "fields".* FROM "fields"
  ↳ app/views/trials/_form.html.erb:39
Rendered trials/_form.html.erb (15.3ms)
  Rendered trials/edit.html.erb within layouts/application (16.6ms)
  Rendered partials/_top_nav.html.erb (0.5ms)
  Rendered partials/_main_nav.html.erb (0.8ms)
Completed 200 OK in 63ms (Views: 46.9ms | ActiveRecord: 8.2ms)

1 个答案:

答案 0 :(得分:8)

表单代码在我看来不正确,第一个分组的集合应该类似于:

<%= f.grouped_collection_select :property_id, Cooperator.order('last_name'), :properties, :full_name, :id, :name %>#请注意,cooperator_idid替代,因为这是选择时应设置的值。您的原始代码会将其设置为合作者的ID,而不是Property。

类似地,第二个应该是这样的:

<%= f.grouped_collection_select :field_id, Property.order('name'), :fields, :name, :id, :field_name %>