Rails Nested Forms Not Updating Nested Model

删除回忆录丶 提交于 2019-12-07 22:58:05

问题


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


来源:https://stackoverflow.com/questions/24589400/rails-nested-forms-not-updating-nested-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!