未定义的方法`values_at”使用nested_form宝石

问题描述:

我使用nested_form宝石未定义的方法`values_at”使用nested_form宝石

这里时收到错误

ActionView::Template::Error (undefined method `values_at' for nil:NilClass): 

是我的代码

模型

class Poll < ActiveRecord::Base 

    attr_accessible :question, :poll_answers_attributes 
    has_many :poll_answers 
    accepts_nested_attributes_for :poll_answers 
end 

class PollAnswer < ActiveRecord::Base 
    belongs_to :poll 
    attr_accessible :answer 
end 

查看

=nested_form_for [:admin, @poll], mutipart: true, class: "form-horizontal" do |f| 
    .span6 
     .control-group 
     =f.label :question, class: "control-label" 
     .controls 
      =f.text_field :question, rows: "5", class: "span5" 
     = f.link_to_add "Add a Answer", :poll_answers 
     =f.submit "Create Post", class: "btn btn-primary" 

堆栈跟踪

/home/abid/.bundler/ruby/1.9.1/nested_form-6232dd853c27/lib/nested_form/builder_mixin.rb:41:in `block in link_to_add' 
/home/abid/.bundler/ruby/1.9.1/nested_form-6232dd853c27/lib/nested_form/view_helper.rb:53:in `call' 
/home/abid/.bundler/ruby/1.9.1/nested_form-6232dd853c27/lib/nested_form/view_helper.rb:53:in `after_nested_form_callbacks' 
/home/abid/.bundler/ruby/1.9.1/nested_form-6232dd853c27/lib/nested_form/view_helper.rb:8:in `block in nested_form_for' 

什么想法?

正如文件中所提及的nested_form宝石,你以前link_to_load按钮提嵌套对象的field_for。我以前没有使用这个gem,但是在阅读文档之后,我猜测这个。

这里的形式看起来像

<%= nested_form_for [:admin, @poll], mutipart: true, class: "form-horizontal" do |f| %> 
    <%= f.text_field :question %> 
    <%= f.fields_for :poll_answers do |poll_ans_form| %> 
    <%= poll_ans_form.text_field :name %> 
    <%= poll_ans_form.link_to_remove "Remove this task" %> 
    <% end %> 
    <p><%= f.link_to_add "Add a Answer", :poll_answers %></p> 
<% end %> 

你应该检查出simple_form做这种类型的嵌套窗体。这很容易。根据你的模型发布,这样的事情应该工作:

# controller 
    def new 
    @poll = Poll.new 
    end 

# new.html.erb 
<%= simple_form_for @poll do |f| %> 
    <%= f.simple_fields_for :poll_answer do |l| %> 
    <%= l.input :answer, autofocus: true %> 
    <%= l.submit "Add", class: 'small round button' %> 
    <% end %> 
<% end %> 

那么这个职位应该得到发送到投票#创建控制器,如果你有开放的路线。从那里,你可以在上面运用你的逻辑。

希望有所帮助。

+0

我需要添加在运行时的答案,可以有3,4,5任意数量的答案,因此多数民众赞成为什么我使用nested_form宝石 – Abid 2013-03-22 15:44:13