记录使用field_for时出现无效问题,即使属性存在,验证也失败?



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

这个问题有3个相关的模型,person_in_needdistricthelp。一个person_in_needhas_manyhelps,belongs_to一个district.一个helpbelongs_to一个district,一个districthas_manyhelps

以下是注册新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中命名对象的方式有关,但玩弄它没有效果。我可以看到该地区在日志中,那么为什么它说它不存在?感谢您的阅读!

在通读了 Rails 文档后,我向我的帮助模型添加了validates_presence_of :user,这解决了问题。

替换

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

编辑:您能否也添加:idhelps_attributes的强参数,如下所示:

helps_attributes: [:id, :help_type, :description, :districts_id]

最新更新