嵌套表单可在“ has_many through”多对多关系中创建许多新的关联对象

时间:2019-04-19 11:20:34

标签: ruby-on-rails

我在DailyQuestionSets和Questions之间有很多关系。我在问答之间有一对多的关系。我在解决问题时遇到的麻烦是如何构建正确的嵌套表单,该嵌套表单可以检索带有一组显示问题文本的标签以及带有答案的表单域的问题集,该表单域将被发布到Answer模型中。 / p>

型号:

class Question < ApplicationRecord
  has_many :dailyquestions, foreign_key: 'dailyquestion_id'
  has_many :dailyquestionsets, :through => :dailyquestions
end

class DailyQuestion < ApplicationRecord
  belongs_to :daily_question_set
  belongs_to :question
end

class DailyQuestionSet < ApplicationRecord
  has_many :daily_questions, foreign_key: 'question_id'
  has_many :questions, :through => :daily_questions, :source => :question
end

class Answer < ApplicationRecord
  belongs_to :users
  belongs_to :questions
  belongs_to :dailyquestionset
end

查看:

<p id="notice"><%= notice %></p>

<%= form_tag('/answers/answerquestions') do %>
  <% @questions.each do |q| %>
    <%= fields_for '@answers[]', Answer do |a| %>

      <div class="field">
        <%= q.label :content %><br>
        <%= a.text_field :answer_text %>
      </div>

    <% end %>
  <% end %>
  <div class="actions">
    <%= submit_tag %>
  </div>
<% end %>

控制器:

  def answerquestions
    @dailyquestionset = DailyQuestionSet.get_today_dailyquestionset
    @questions = @dailyquestionset.questions
    @answers = []
    @questions.count.times do
      @answers << Answer.new
  end 

问题是我无法在视图中从q(问题)中获取标签值,这不足为奇,因为我对如何构造此嵌套形式语法大胆猜测。

undefined method `label' for #<Question:0x00007f54383ce748>
Extracted source (around line #8):
      <div class="field">
        <%= q.label :content %><br>
        <%= a.text_field :answer_text %>
      </div>

任何有关如何正确处理表单的想法都受到赞赏:)

1 个答案:

答案 0 :(得分:0)

似乎您正在尝试创建一个文本字段和一个相关标签,并使用从Questions的{​​{1}}属性中获取的文本:

content

<div class="field"> <%= a.label :answer_text, q.content %><br> <%= a.text_field :answer_text %> </div> label上的方法,所需的文本(此处为FormBuilder)作为第二个参数传递。参见documentation