gpt4 book ai didi

ruby-on-rails - Rails 嵌套表单不更新嵌套模型

转载 作者:行者123 更新时间:2023-12-04 16:49:40 25 4
gpt4 key购买 nike

我在尝试更新表单中的嵌套模型时遇到问题。我没有收到任何错误,但属性没有更新。

我有以下模型:

class Trip < ActiveRecord::Base
has_many :segments
accepts_nested_attributes_for :segments, allow_destroy: true
end

class Segment < ActiveRecord::Base
belongs_to :start_location, class_name: 'Location'
belongs_to :end_location, class_name: 'Location'
belongs_to :trip

validates_presence_of :date, :start_location, :end_location
end

class Location < ActiveRecord::Base
has_many :segments
end

并在 _form.html.erb 中包含此代码:

<%= form_for @trip do |f| %>
...
<%= f.fields_for :segments do |builder| %>
<%= render 'segment_fields', f: builder %>
<% end %>
...
<% end %>

这在部分 _segment_fields.html.erb 中:

<%= f.collection_select :start_location_id, Location.order(:name), :id, :name %> -
<%= f.collection_select :end_location_id, Location.order(:name), :id, :name %> <br>
<%= f.date_field :date %>

在我的 Controller 中,我还允许分配 :segments_attributes

def trip_params
params.require(:trip).permit(:name, :start_date, :end_date, :segments_attributes)
end

有人知道我缺少什么或做错了什么吗?

最佳答案

当您创建新记录时,您不需要允许其id,因为它尚未被创建,但您需要时更新您的记录,您需要将 id 传递给允许的属性,否则它将与 create 一起使用,但在您想要更新记录时不起作用,因此您需要执行以下操作:

def trip_params
params.require(:trip).permit(:id, :name, :start_date, :end_date, segments_attributes: [:id,:start_location_id,:end_location_id, :date])
end

关于ruby-on-rails - Rails 嵌套表单不更新嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com