Rails嵌套表单不更新嵌套模型

时间:2014-07-05 18:33:34

标签: ruby-on-rails ruby-on-rails-4 nested-forms update-attributes

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

我有以下型号:

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

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

1 个答案:

答案 0 :(得分:1)

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

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