I have a many to many relationship between DailyQuestionSets and 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.
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:
<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. See documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.