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

时间:2022-08-25 05:02:25

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.

我只是检查时可以看到哪些作品:@ user_question_group.user_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.

但是当我真的想要显示表单时,它只显示问题的一个表单,即使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 %>
...

Does anyone know what's wrong with my form?

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

1 个解决方案

#1


3  

try to use fields_for as a method of the form, this way:

尝试使用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 %>
...

#1


3  

try to use fields_for as a method of the form, this way:

尝试使用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 %>
...