Rails Nested Forms Not Updating Nested Model

2019-05-23 02:06发布

问题:

I am having trouble trying to update nested models in my form. I don't get any errors and but the attributes don't get updated.

I have the following model:

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

And have this code in the _form.html.erb:

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

And this in the partial _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 %>

In my controller I also permited the assigment of :segments_attributes

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

Does anybody know what I am lacking or doing wrong?

回答1:

When you are creating a new record you don't need its id to be permitted as it's not been created but when you want to update your record you need to pass id to the permitted attributes, else it will work with create but not when you want to update your record, so you need to do:

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