0

I have Users who need to answer some questions upon registering. Users has_many Questions through an Answers join table. I am just trying figure out how to create the form on the Users#new action. I am using simple_form. Here is my DB Schema:

ActiveRecord::Schema.define(:version => 20120831144008) do

  create_table "answers", :force => true do |t|
    t.integer  "user_id"
    t.integer  "question_id"
    t.text     "response"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  add_index "answers", ["user_id", "question_id"], :name => "index_answers_on_user_id_and_question_id"

  create_table "questions", :force => true do |t|
    t.string   "title"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "users", :force => true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
  end

end

So on the users#new page, I am looping through the question titles, and need to create a text area below each question and have it get created. here is what I have for a form so far, it doesn't work and probably wont help much for a solution but.

<%= simple_form_for(@user) do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.input :email %>
  <%= f.input :phone %>
  <%= f.input :organization %>
  <%= f.input :primary_contact %>
  <%= f.association :answers, collection: @questions %>
  <% @questions.each do |question| %>
    <div>
      <strong><%= question.title %></strong>
      <%= text_field_tag 'questions[]' %>
    </div>
  <% end %>
  <%= f.button :submit %>
<% end %>

Solution

I was able to get this to work, not sure if this is the absolute correct way but it's not completely ugly. In my controller I have @user.answers.build and in my simple_form I loop through questions, and create an answer field with the required data filled in.

  <% Question.all.each do |question| %>
    <%= f.simple_fields_for :answers do |a| %>
      <div>
        <strong>
          <%= question.title %>
        </strong>
        <%= a.hidden_field :question_id, value: question.id %>
        <%= a.input :response, label: false %>
      </div>
    <% end %>
  <% end %>
Ryan Haywood
  • 549
  • 1
  • 8
  • 21

1 Answers1

0

I believe you will need to do:

<%= simple_fields_for @questions.each do |question| %>

to ensure that you get the nested form fields.

Harry
  • 4,660
  • 7
  • 37
  • 65
  • hey, was not really able to follow this logic too well. I updated my question with a working solution, may not be the prettiest though. Thanks for replying! – Ryan Haywood Aug 31 '12 at 19:07