嵌套表单只显示一个属性的文本字段,但应该是三个?

时间:2012-03-05 04:44:28

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

我的嵌套表单有问题。

型号:

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

和另一个:

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

所以我在控制器中创建了问题:

  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

当我检查时,我可以看到哪些作品:@ user_question_group.user_questions。我可以看到所有问题。

但是当我真的想要显示表单时,它只会显示一个问题的表单,即使question_id应该有一个数字,它甚至是空的。

...
<%= 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 %>
...

有谁知道我的表格有什么问题?

1 个答案:

答案 0 :(得分:3)

尝试使用fields_for作为表单的方法,这样:

...
<%= 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 %>
  <%= f.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 %>
...