简体   繁体   English

嵌套表单以'has_many到'多对多关系创建许多新的关联对象

[英]Nested form to create a number of new associated objects in a 'has_many through' many to many relationship

I have a many to many relationship between DailyQuestionSets and Questions. DailyQuestionSets和Questions之间有很多关系。 I have a one to many relationship between Questions and Answers. 我在问题和答案之间有一对多的关系。 What I am having trouble working out is how to build the right kind of nested form that could retrieve a set of Questions with a label showing the question text as well as a form field with the answer which would get posted to the Answer model. 我在解决问题时遇到的问题是如何构建正确的嵌套表单,该表单可以检索一组带有显示问题文本的标签的问题,以及一个带有答案的表单字段,该答案将发布到答案模型。

Models: 楷模:

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

View: 视图:

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

Controller: 控制器:

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

The problem is that I'm not able to get a label value out of q (Question) in the view and this is no surprise as I have taken a wild guess as to how to construct this nested form syntax. 问题是我无法从视图中的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>

Any ideas on how to handle the form correctly most appreciated :) 关于如何正确处理表单的任何想法最受赞赏:)

It seems you are trying to create a text field and a related label with text taken from the Questions 's content property: 您似乎正在尝试使用从Questionscontent属性中获取的文本创建文本字段和相关标签:

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

ie label is a method on the FormBuilder and the desired text (here q.content ) is passed as second argument. ie labelFormBuilder上的一个方法,所需的文本(此处为q.content )作为第二个参数传递。 See documentation . 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM