Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `values_at' using nested_form gem

I am getting the error

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

when using nested_form gem

Here is my code

Models

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

View

 =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"

StackTrace

/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'

Any Ideas ?

like image 512
Abid Avatar asked Mar 22 '13 15:03

Abid


2 Answers

As mentioned in the documentation for the nested_form gem, you have to mention the field_for of the nested object before link_to_load button. I haven't use this gem previously but after going through the documentation, i am guessing this.

Here the form looks like

<%= 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 %>
like image 142
Sagar Bommidi Avatar answered Oct 24 '22 04:10

Sagar Bommidi


You should check out simple_form for doing this type of nested form. It makes it pretty easy. Based on your models you posted, something like this should work:

# 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 %>

Then that post should get sent to the poll#create controller if you have the route open. From there, you can work your logic on it.

Hope that helps.

like image 44
jbearden Avatar answered Oct 24 '22 04:10

jbearden