嵌套属性表单。如何缩小fields_for的内容?

时间:2015-09-15 09:51:19

标签: ruby-on-rails ruby-on-rails-4

我有类似的东西:

class Event < ActiveRecord::Base
  has_many :weeks, dependent: :destroy
  has_many :tests, through: :weeks

  accepts_nested_attribues_for :weeks, allow_destroy: true
  accepts_nested_attribues_for :tests, allow_destroy: true
end

class Week < ActiveRecord::Base
  belongs_to :event
  has_many :tests, dependent: :destroy
end

class Test < ActiveRecord::Base
  belongs_to :week
end

注意:这些模型并不真实,它们与我所拥有的相比过于简单。

我在视图(haml)上有这样的东西:

=form_for @event do |e|
  %h3 Event
  =render 'form', e: e # This partial contains the general data of the Event.

  %h3 Weeks

  %table
    %thead
      %th Start
      %th End
      %th X
    %tbody
      =e.fields_for :weeks do |w|
        =render 'week_fields', w: w
  =link_to_add_fields 'Add Week', e, :weeks # Custom helper that adds the fields of the week to the end of the table via JavaScript.

  %h3 Tests

  %table
    %thead
      %th Field 1
      %th Field 2
      %th Field 3
      %th X
    %tbody
      =e.fields_for :tests do |t|
        =render 'test_fields', t: t
  =link_to_add_fields 'Add Test', e, :tests

这将直接工作,除了最后一部分(我为每个测试添加数据)将不允许我指定测试属于哪个周(除非我添加类似选择框的内容)。所以,为了减轻这种情况,我将其更改为:

  %h3 Tests

  -@weeks.each do |week|
    %h5=week.start # Prints the 'start' of the Week.
    %table
      %thead
        %th Field 1
        %th Field 2
        %th Field 3
        %th X
      %tbody
        =e.fields_for :tests do |t|
          =render 'test_fields', t: t, w: week.id
    =link_to_add_fields 'Add Test', e, :tests, parent: week.id

这将为每个周显示一个不同的表,但由于我没有缩小fields_for范围,它显示每个周块的所有测试,而不是仅包括该个体的测试星期。

有没有办法让这个field_for只显示所选周的记录?我已经在进行.each循环,我可以使用该值来缩小fields_for显示的范围吗?

顺便说一句,请注意我在渲染和自定义帮助器上发送week.id。这样,一旦表单提交,这两个字段生成的字段都包含week_id值。从理论上讲,render不需要该值,但由于两者都使用相同的部分,我选择在两者上包含该值,以便在不是来自帮助程序时不对部分进行额外验证

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

fields_for接受可选的第二个参数来指定要为其构建字段的模型。如果为空,则rails将使用指定的关联名称来获取记录。在你的情况下,这将成功:

= e.fields_for :tests, week.tests do |t|