I’m having a problem with my nested form.
Models:
class UserAnswer < ActiveRecord::Base
belongs_to :user_questions
belongs_to :question
validates :user_question_group, presence: true
validates :question, presence: true
validates :answer, presence: true
end
and the other one:
class UserQuestionGroup < ActiveRecord::Base
belongs_to :user
has_many :user_answers, dependent: :destroy
accepts_nested_attributes_for :user_answers, :reject_if => lambda { |a| a[:answer].blank? }
validates :user_id, presence: true
end
So I create the question in the controller:
def new
@user_question_group = UserQuestionGroup.new(user_id: current_user.id)
QuestionGroup.all.each do |ag|
ag.questions.each do |a|
@user_question_group.user_questions.build(questions_id: a.id)
end
end
end
Which works which I can see when I simply inspect: @user_question_group.user_questions. I can see all questions.
But when I actually want to show the form it only show one form for the question and it’s even empty even though question_id should have a number.
...
<%= form_for(@user_question_group, :url => user_user_question_groups_path(@current_user)) do |f| %>
<%= f.hidden_field :user_id %>
<%#= @user_question_group.user_questions.inspect %>
<%= fields_for :user_questions do |fa| %>
<p>
<%= fa.label :question_id %>
<%= fa.text_field :question_id %>
</p>
<p>
<%= fa.label :answer %>
<%= fa.text_field :answer %>
</p>
<% end %>
...
Does anyone know what’s wrong with my form?
try to use
fields_foras a method of the form, this way: