Rails 4, retrieved many records with Model.where(related_model_id: 1), how to show each one in an individual view?

不羁岁月 提交于 2019-12-24 21:39:51

问题


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

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

I can show each question in quizzes/show.html.haml view with

- @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!!


回答1:


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...).

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

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


来源:https://stackoverflow.com/questions/27305269/rails-4-retrieved-many-records-with-model-whererelated-model-id-1-how-to-sh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!