Rails 4,使用Model.where(related_model_id:1)检索了许多记录,如何在一个单独的视图中显示每个记录? [英] Rails 4, retrieved many records with Model.where(related_model_id: 1), how to show each one in an individual view?
问题描述
好的,所以我正在做一个测验,作为我的应用程序的一部分.我有三个嵌套模型测验,问题,答案.
Ok so I'm working on a quiz as part of my app. I have three nested models Quiz, Question, Answer.
class Quiz < ActiveRecord::Base
belongs_to :video
has_many :questions
has_many :answers, through: :questions
accepts_nested_attributes_for :questions,
:reject_if => lambda { |a| a[:content].blank? }, allow_destroy: true
end
class Question < ActiveRecord::Base
belongs_to :quiz
has_many :answers
accepts_nested_attributes_for :answers,
:reject_if => lambda { |a| a[:content].blank? }, allow_destroy: true
end
class Answer < ActiveRecord::Base
belongs_to :question
end
在控制器动作测验#show中,我可以使用
In the controller action quizzes#show I am able to retrieve all the questions for a particular quiz with
def show
@quiz = Quiz.find(params[:id])
@question = Question.where(quiz_id: @quiz)
end
我可以使用
- @question.each do |question|
= question.content
问题是上面的代码将同一页面上的所有问题一个接一个地显示在另一个页面上.
The problem is that the above code will show all the questions on the same page one below the other.
我真正想要的是在每个视图中单独显示每个问题,每页显示一个问题.这样,一旦用户回答了一个问题,他们就单击一个按钮,它将用下一个问题重新渲染视图.
What I really want is to show each question individually in its own view, one question per page. So that once the user answers one question, they click on a button and it will re-render the view with the next question.
无论如何,我一直在费劲地试图弄清楚该怎么做.先感谢您!哦,让我知道您是否还需要查看我的代码!
Anyway I'm having a hell of a time trying to figure out how to do this. Thank you in Advance! Oh and let me know if you need to see any more of my code!!
推荐答案
首先:您已经建立了关联(has_many :questions
),因此您可以只使用@quiz.questions
而不是手动搜索(
First of all: you've set up an association (has_many :questions
), so you can just use @quiz.questions
instead of a manual search (Question.where...
).
您只需要指定一个排序顺序,然后根据最小值获取一条记录.假设您选择id
(created_at
或任何自定义字段都应以类似方式工作).
You just need to specify a sort order and then fetch a single record based on a minimum-value. Let's say you choose the id
(created_at
or any custom field should work in a similar way).
def show
@min_id = params[:min_id]
@quiz = Quiz.find(params[:id])
@questions = @quiz.questions.order("id ASC")
if @min_id
@question = @questions.where("id > ?", @min_id).first
else
@question = @questions.first
end
end
然后,您只需将当前问题ID添加到下一个问题的链接即可.可能是这样的(用erb代替haml,但您知道了;)):
You can then just add the current questions id the the link for the next question. Probably something like this (erb instead of haml, but you get the idea ;) ):
<%= @question.content %>
<%= link_to "Next question", quiz_path(@quiz, :min_id => @question.id) %>
这篇关于Rails 4,使用Model.where(related_model_id:1)检索了许多记录,如何在一个单独的视图中显示每个记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!