【问题标题】:Problems with nested form fields showing up出现嵌套表单字段的问题
【发布时间】:2009-05-04 01:04:02
【问题描述】:

我正在尝试为我的网站实现嵌套对象表单,使用 Ryan Daigle 的博客文章作为指南 (http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes)。由于某种原因,嵌套的表单字段不会出现在视图中。

class Instruction < ActiveRecord::Base
  has_many :steps
  accepts_nested_attributes_for :steps
end

class Step < ActiveRecord::Base
  belongs_to :instruction
end

<% form_for @instruction do |instruction_form| %>
  <%= instruction_form.error_messages %>
  <p>
    <%= instruction_form.label :title %><br />
    <%= instruction_form.text_field :title %>
  </p>
  <p>
    <%= instruction_form.label :difficulty %><br />
    <%= instruction_form.text_field :difficulty %>
  </p>

<% instruction_form.fields_for :steps do |step_form| %>
    <%= step_form.label :explanation, 'Explanation: ' %>
    <%= step_form.text_field :explanation %>

<% end %>

  <p><%= instruction_form.submit "Submit" %></p>
<% end %>

当我将 instruction_form.fields_for :steps do |step_form| 更改为 instruction_form.fields_for :step do |step_form| 时,表单会呈现,但在提交时,我收到“未知属性:步骤”错误。

我正在做的似乎与教程相匹配。我应该检查什么?谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby nested-forms


    【解决方案1】:

    您的控制器中发生了什么?我还没有阅读教程,现在似乎无法将其拉起(向下?)但是您是否要在内存中构建一个对象来填充?

    在您的控制器中,在您的“新”操作中,确保您是

    @instruction = Instruction.new
    @instruction.steps.build
    

    这将在内存中将Step 实例化为“占位符”,供您填写表单。 . .至少这是我在使用accepts_nested_attributes_for 时在自己的控制器中所做的,而且效果很好。

    让我知道它是否有效,一旦我可以提取教程,我可能需要编辑它

    【讨论】:

    • 我知道我需要@instruction = Instruction.new 不知道我需要做@instruction.steps.build。回顾教程,我意识到我应该阅读“附加”部分。感谢您的帮助!
    • 太棒了!这是在黑暗中拍摄的,但是当我开始使用 accept_nested_attributes_for 欢呼时,我注意到了奇怪的事情!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    相关资源
    最近更新 更多