我找到了很多关于这个Railscast的帖子,但所有的建议都没有帮助我。我已经能够在视图中呈现一个嵌套的表单字段,但只有一个,而不是我在控制器中调用的 3 个。 提交时,出现错误:无法批量分配受保护的属性:线索
第章.rb
class Chapter < ActiveRecord::Base
belongs_to :trail
has_many :clues, :dependent => :destroy
accepts_nested_attributes_for :clues
attr_accessible :asset, :assetkind, :description, :gate, :name, :trail, :trail_id, :cover
.
.
.
end
线索.rb
class Clue < ActiveRecord::Base
attr_accessible :chapter_id, :theclue, :typeof, :chapter
.
.
.
belongs_to :chapter
end
在 railcast 中,它说使用等效的 :clues,这渲染了 3 个字段。 但在我的版本中,它没有渲染田野。 相反,我使用 @chapter.clues,它只呈现一个。
我制作新篇章时的表格。
<h1>Add a New Chapter</h1>
<h3>Add To Trail : <%= @trail.title %></h3><br>
<%= form_for [@trail, @trail.chapters.build] do |f| %>
<h6>About the Chapter</h6>
<%= f.label :name, 'Chapter Name' %>
.
.
.
<h6>Progressing the Story</h6>
<%= f.fields_for @chapter.clues do |builder| %>
<p>
<%= builder.label :theclue, "Enter Clue" %>
<%= builder.text_area :theclue, :rows => 2 %>
</p>
<% end %>
.
.
.
<% end %>
我的chapters_controller.rb 新
class ChaptersController < ApplicationController
def new
@trail = Trail.find(params[:trail_id])
@chapter = Chapter.new
@title = "Chapter"
3.times { @chapter.clues.build }
logger.debug "CHAPTER!!!!!!!!!!!!new: am i in a trail? #{@trail.to_yaml}"
logger.debug "CHAPTER!!!!!!!!!!!!new: am i in a clue? #{@chapter.clues.to_yaml}"
end
我的日志显示我 3 条线索,但属性为空(无 :id(。 这是不对劲的迹象吗? 因此,即使我的日志显示 3 个线索对象,我的视图也只显示一个。
思潮? 由于对堆栈溢出的建议,我已经添加到 chapter.rb
attr_accessible :clues_attributes
并且没有运气,无论有没有,都有相同的行为和错误。
提前感谢您的时间
我自己想通了。 不知道为什么,我会推测,如果我不在,欢迎有人更好地解释它。
问题就在这里:
<%= form_for [@trail, @trail.chapters.build] do |f| %>
我改成了:
<%= form_for @chapter do |f| %>
然后我不得不在我的chapters_controller中改变一些东西,使小径成为对象并捕获 ID。 但是,在我进行此更改后,我的 3 个线索字段开始显示在视图中,并且我关于批量分配的错误消失了。
我认为我之前创建的章节是空的,并没有真正生成,只保存信息,所以试图用线索form_for保存嵌套信息是临时数据的另一步......在我的控制器中创建对象然后用表单填充它更实质性的地方......我知道真正的技术...就像我说的,我让它工作了,不要问我如何...但我开始理解Rails是怎么想的。
提交时,出现错误:无法批量分配受保护的属性:线索
这告诉您该属性受到批量分配的保护。基本上,您能够设置它的唯一方法是通过代码中的方法,而不是通过用户输入。(通常通过模型上的update_attributes进行分配。
你需要做的是在models/chapter.rb中添加:clue到attr_accessible。
您可能还想添加 :clues - 我认为它实际上应该给您:clues 受到保护的错误。您可能会遇到 :clue_ids 的问题。无论它说什么都是受保护的,只需在该模型中放入 attr_accessible 方法,您应该能够从用户输入中更新它。