使用field_for记录无效,即使属性存在验证也失败?

问题描述 投票:0回答:1

我目前正在Rails 6.0和Ruby 2.5的网站上工作。简而言之,该网站是将需要帮助的人与可以帮助的人联系在一起,并提供所需帮助的描述。

此问题有3个相关模型,person_in_needdistricthelpperson_in_need具有很多helps,并且属于districthelp属于一个districtdistrict has_many helps

下面是与他们需要的person_in_need一起签署新的help的表格。

<%= form_with model: @person_in_need, url: persons_in_need_index_path do |form| %>
    <%= form.label :name %>
    <%= form.text_field :name%>
    <br>
    <%= form.label :phone_number %>
    <%= form.phone_field :phone_number %>
    <br>
    <%= form.fields_for :helps do |help_form| %>
        <%= help_form.label :districts_id %>
        <%= help_form.grouped_collection_select :districts_id, State.order(:name), :districts, :name, :id, :name, include_blank: true %>
        <br>
        <%= help_form.label 'What kind of help do you need?' %>
        <%= help_form.select :help_type, options_for_select(Help.help_types.keys), include_blank: true %>
        <%= help_form.label 'Describe' %>
        <%= help_form.text_area :description %>
    <% end %>
    <%= form.submit 'Post' %>
<% end %>

控制器

class PersonsInNeedController < ApplicationController
    def new
        @person_in_need = PersonInNeed.new
        @person_in_need.helps.new
    end

    def create
        @person_in_need = PersonInNeed.create!(person_in_need_params)
        @person_in_need.helps.first.person_in_need_id = @person_in_need.id
        if @person_in_need.save
          redirect_to root_path 
        else
          redirect_to new_persons_in_need_path
        end
    end

    private

    def person_in_need_params
      params.require(:person_in_need).permit(:name, :phone_number, helps_attributes: [:help_type, :description, :districts_id])
    end
end

下面是日志

Parameters: {"authenticity_token"=>"eUmMHFVFcpRsO7cGzP2nJ/MAkM/Q6IDA/oPUrWNL1bBox53MqGLnAtklO1s6FVppoX3c8E1IADAGND+Q/74FwA==", "person_in_need"=>{"name"=>"Sar", "phone_number"=>"012345", "helps_attributes"=>{"0"=>{"districts_id"=>"Dungun", "help_type"=>"food", "description"=>"need rice"}}}, "commit"=>"Post"}

ActiveRecord::RecordInvalid (Validation failed: Helps district must exist):

[当我尝试保存数据时,它在日志中返回上述错误,我怀疑这可能与如何在grouped_select_form中命名我的对象有关,但是尝试这样做没有任何效果。我可以看到该分区中有日志,为什么它说它不存在?感谢您的阅读!

ruby-on-rails ruby activerecord rails-activerecord ruby-on-rails-6
1个回答
0
投票

替换

<%= help_form.grouped_collection_select :districts_id, State.order(:name), :districts, :name, :id, :name, include_blank: true %>

<%= help_form.grouped_collection_select :districts_id, State.order(:name), :districts, :id, :name, :name, include_blank: true %>

编辑:您也可以在:id的强参数中添加helps_attributes,如下所示:

helps_attributes: [:id, :help_type, :description, :districts_id]
© www.soinside.com 2019 - 2024. All rights reserved.