我在尝试更新表单中的嵌套模型时遇到麻烦。我没有任何错误,但是属性没有更新。
我有以下模型:
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 %>
在我的控制器中,我还允许: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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句