Rails嵌套表格不会更新嵌套模型 [英] Rails Nested Forms Not Updating Nested Model

查看:88
本文介绍了Rails嵌套表格不会更新嵌套模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试更新表单中的嵌套模型时遇到麻烦.我没有任何错误,但是属性没有更新.

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.

我有以下模型:

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中:

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 %>

这在_segment_fields.html.erb部分中:

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 %>

在我的控制器中,我还允许设置:segments_attributes

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?

推荐答案

创建新记录时,您无需允许其 id ,因为它是尚未创建,但 当您想更新记录时,需要将ID传递给允许的属性 ,否则它将与create一起使用,但在您想更新记录时不起作用,所以您需要这样做:

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

这篇关于Rails嵌套表格不会更新嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆