Search code examples
ruby-on-railsformtastic

How to loop through two alternating resources on a form?


I'm trying to make a dynamic form of questions and answers, like so:

Question _______

Answer _______

Question _______

Answer _______

I can't figure out how to loop through the two resources as alternating pairs. I have tried this:

<%= semantic_fields_for [@question, @answer] do |h, i| %>
  <%= f.inputs :for => @question do |h|%>
    <%= h.input :question %>
  <% end %>
  <%= f.inputs :for => @answer do |i|%>
    <%= i.input :answer %>
  <% end %>
<% end %>

But it gives me the error "Undefined method `model_name' for Array:Class."

My controller:

def new

  @post = Post.new
  @question = @post.questions.new
  @answer = @question.build_answer

  respond_to do |format|
    format.html
  end
end

And my models:

class Post < ActiveRecord::Base
  has_many :questions
  has_many :answers
end
class Question < ActiveRecord::Base
  belongs_to :post
  has_one :answer
end
class Answer < ActiveRecord::Base
  belongs_to :question
  belongs_to :post
end

Solution

  • So I don't personally use formtastic but I understand it follows similar lines to simple_form. Your error is coming from trying to pass an Array to semantic_fields_for which only takes a single object:

    <%= semantic_form_for @questions do |q| %>
      <%= q.input :question %>
      <%= q.semantic_fields_for @answer do |a| %>
        <%= a.inputs :answer %>
      <% end %>
      <%= q.actions %>
    <% end %>
    

    Don’t forget your models need to be setup correctly with accepts_nested_attributes_for

    class Question < ActiveRecord::Base
      belongs_to :post
      has_one :answer
      accepts_nested_attributes_for :answers
    end
    

    You'll want to check out the formtastic docs at https://github.com/justinfrench/formtastic

    That should get your form showing correctly in the view but you'll need to add some more to your questions controller to make sure it saves the answers (someone correct me if I'm mistaken).

    Also just so it's clear do your Questions and Answers tables really have a question and answer column? If the columns are actually something like :body you'll want to replace the relevant symbols in the above code.