代码之家  ›  专栏  ›  技术社区  ›  DollarChills

保存时选择不工作

  •  7
  • DollarChills  · 技术社区  · 6 年前

    我在用 grouped_collection_select

    第一个 分组\u集合\u选择 财产 筛选出与 合作者 过滤时不起作用 领域 关联到 ,但在尝试保存时出现错误:

    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 %>
    

    当我换衣服的时候 分组\u集合\u选择 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 回复  |  直到 6 年前
        1
  •  9
  •   Chirag    6 年前

    我觉得表单代码不对,第一个分组集合应该是这样的:

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

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

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