【问题标题】:undefined method `values_at' using nested_form gem使用nested_form gem的未定义方法`values_at'
【发布时间】:2013-03-22 15:27:11
【问题描述】:

我收到了错误

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

使用nested_form gem 时

这是我的代码

型号

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'

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    正如 nested_form gem 的文档中所述,您必须在 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 %>
    

    【讨论】:

      【解决方案2】:

      您应该查看 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 %>
      

      如果你打开了路由,那么该帖子应该被发送到 poll#create 控制器。从那里,您可以对其进行逻辑处理。

      希望对您有所帮助。

      【讨论】:

      • 我需要在运行时添加答案,可以有 3、4、5 个任意数量的答案,这就是我使用nested_form gem 的原因
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 2016-06-24
      • 2014-09-02
      • 1970-01-01
      相关资源
      最近更新 更多