这是父模型:
class TypeWell < ActiveRecord::Base
...
has_many :type_well_phases, :dependent => :destroy
accepts_nested_attributes_for :type_well_phases, :reject_if => lambda { |a| a[:phase_id].blank? }, :allow_destroy => true
...
end
这是嵌套模型:
class TypeWellPhase < ActiveRecord::Base
belongs_to :type_well
belongs_to :phase
end
这是阶段模型:
class Phase < ActiveRecord::Base
...
has_many :type_well_phases
...
end
我通过从父模型的 Controller 中的阶段(阶段模型)表中复制所有记录来在子表(TypeWellPhases)中添加嵌套记录,如下所示:
class TypeWellsController < ResourceController
...
def new
@new_heading = "New Type Well - Computed"
@type_well = TypeWell.new
initialize_phase_fields
end
private
def initialize_phase_fields
Phase.order("id").all.each do |p|
type_well_phase = @type_well.type_well_phases.build
type_well_phase.phase_id = p.id
type_well_phase.gw_heat_value = p.gw_heat_value
end
end
...
end
我这样做是因为我想通过添加的子字段保持特定的顺序。代码 Phase.order("id") 的一部分就是为此,因为阶段表具有特定顺序的这些记录。
在此之后,我使用 simple_form_for 和 simple_fields_for 助手,如下所示在我的表单部分中:
= simple_form_for @type_well do |f|
...
#type_well_phases
= f.simple_fields_for :type_well_phases do |type_well_phase|
= render "type_well_phase_fields", :f => type_well_phase
一切都按预期工作;大部分的时间。但是,有时表单中子行的顺序在保存后会变得困惑。顺序在此应用程序中很重要,这就是为什么我在 Controller 的私有(private)方法中显式执行此排序的原因。
我正在使用“茧” gem 添加删除子记录。我不确定为什么这个订单有时会搞砸。
很抱歉这么长的帖子,但我想预先提供所有相关的细节。
感谢任何指针。
巴拉特
最佳答案
我将以更通用的方式向您解释。假设您有 Product 和 Order 模型:
= form_for @product do |f|
...
= f.fields_for :orders do |order_fields|
= order_fields.text_field :name
如果您希望您的订单按名称排序,那么只需对它们进行排序:)
代替:
= f.fields_for :orders do |order_fields|
放:
= f.fields_for :orders, f.object.orders.order(:name) do |order_fields|
如您所见,
f
作为 form_for
block 的参数的变量有方法object
.这是您的@product,因此您可以通过 .orders
获取其订单然后通过 .order(:name)
应用所需的排序(对不起这个小小的困惑:订单/订单)。您可以将排序顺序作为
fields_for
的第二个参数传递的解决方案的关键.附言您使用 simple_form gem 不会影响我的解决方案。如果您将“simple_”添加到助手中,它将起作用。只是希望我的回答对其他人更有帮助,而不是太与任务相关。
关于ruby-on-rails - 在 Rails 应用程序中使用 accept_nested_attributes_for 时如何维护嵌套属性的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10505853/