我有一个评估模型,其中有很多答案。我正在尝试构建我的f.fields_for,但收到错误:
"undefined method `content' for <Answer::ActiveRecord_Associations_CollectionProxy:0x007fdb12041fd8>"
查看:
<%= f.fields_for @answers do |builder| %>
<%= builder.text_area :content, :class=>"form-control question-field", :data => {:question => question.id} %>
<% end %>
控制器:
def edit
@assessment = current_user.assessments.find(params[:id])
@answers = @assessment.answers
end
我理解错误似乎是我在集合上调用方法而不是单个对象。但我不明白如何解决它。
答案 0 :(得分:0)
如果f
是@assassment
的构建者,您可以执行以下操作:
<%= f.fields_for :answers do |builder| %>
<%= builder.text_area :content, :class=>"form-control question-field", :data => {:question => question.id} %>
<% end %>
您的Assassement
模型中还需要此功能:
class Assasement < ActiveRecord::Base
has_many :answers
accepts_nested_attributes_for :answers
#...
end
答案 1 :(得分:0)
#fields_for
期望object_name
作为第一个参数或object
- 但没有集合。因此,您有两种选择,即强调上下文。要么隐式地从外层表单助手(f
)获取子集合:
<%= f.fields_for :answers do |builder| %>
或者将特定集合作为第二个参数传递,如下所示:
<%= f.fields_for :answers, @answers do |builder| %>
规格:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for