我在尝试更新表单中的嵌套模型时遇到问题。我没有收到任何错误,但属性没有更新。
我有以下模型:
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 %>
在我的控制器中,我还允许分配 :segment_attributes
def trip_params
params.require(:trip).permit(:name, :start_date, :end_date, :segments_attributes)
end
有人知道我缺少什么或做错了什么吗?