Ruby on rails 如何?Rails根据tag_id使用上一个/下一个视图随机排列立柱
所以我想在我的rails应用程序上有一个链接,链接到一个视图,该视图显示一个特定标签id的随机问题 这个用例是我的班级的一个测验应用程序,我们有N个标签,有N个问题。每个问题可以有多个标签 我想有一种方法可以随机显示(阅读:任何人都不应该有相同的问题顺序),但仍然可以通过单击视图中的“上一步/下一步”来执行所有具有特定标记id的问题 我知道了如何在视图中显示某个标记的所有问题,但我仍然无法为某个标记随机显示上一个/下一个。例如:当用户单击链接时,它应该随机生成或列出标记id的所有问题,并且只能在该视图中访问该标记id。每个人都会问同样的问题,只是顺序不同 我意识到有很多优点,但我想先学习和理解如何从头开始 问题/show.html.erbRuby on rails 如何?Rails根据tag_id使用上一个/下一个视图随机排列立柱,ruby-on-rails,ruby,random,Ruby On Rails,Ruby,Random,所以我想在我的rails应用程序上有一个链接,链接到一个视图,该视图显示一个特定标签id的随机问题 这个用例是我的班级的一个测验应用程序,我们有N个标签,有N个问题。每个问题可以有多个标签 我想有一种方法可以随机显示(阅读:任何人都不应该有相同的问题顺序),但仍然可以通过单击视图中的“上一步/下一步”来执行所有具有特定标记id的问题 我知道了如何在视图中显示某个标记的所有问题,但我仍然无法为某个标记随机显示上一个/下一个。例如:当用户单击链接时,它应该随机生成或列出标记id的所有问题,并且只能在
<strong>tags</strong><br>
<%= @question.tags.map{|t| t.name}.join(", ") %>
<%= link_to "Previous Question", @question.previous %>
<%= link_to "Next Question", @question.next %>
标签
这是我的问题
class QuestionsController < ApplicationController
def new
@question = Question.new
end
def index
if params[:tag_id].present?
tag = Tag.find(params[:tag_id])
@questions = tag.questions
else
@questions = Question.all
end
end
def show
@question = Question.find(params[:id])
end etc etc ... [rest of code here is redacted as its not relevant]
end
类问题控制器
这是我的问题.rb模型
class Question < ActiveRecord::Base
has_many :taggings
has_many :tags, through: :taggings
#links this to the user.rb model?
belongs_to :user
scope :next, lambda {|id| where("id > ?",id).order("id ASC") } # this is the default ordering for AR
scope :previous, lambda {|id| where("id < ?",id).order("id DESC") }
def next
Question.next(self.id).first
end
def previous
Question.previous(self.id).first
end
end
类问题?”,id).order(“id ASC”)}这是AR的默认顺序
范围:previous,lambda{id | where(“id<?”,id).order(“id DESC”)}
def下一个
问题。下一个(self.id)。第一个
结束
def先前版本
问题。上一个(self.id)。第一个
结束
结束
tag.rb
class Tag < ActiveRecord::Base
has_many :taggings
has_many :questions, through: :taggings # notice the use of the plural model name
end
class标记
tagging.rb
class Tagging < ActiveRecord::Base
belongs_to :question # foreign key - post_id
belongs_to :tag # foreign key - tag_id
end
类标记
您可以使用该方法,并使用当前用户的id
对其进行种子设定。像这样的
@questions = Question.next.shuffle(random: Random.new(current_user.id))
@questions = Question.prev.shuffle(random: Random.new(current_user.id))
@questions = tag.questions.shuffle(random: Random.new(current_user.id))
这样,即使有多个页面刷新,该用户的顺序也将相同。每个用户都有不同的顺序。您必须为每个用户存储生成的随机顺序(例如,在数据库中,可能是会话或cookie中)。否则,您将记不起访问者在以下请求中已经看到或仍然需要看到的问题。换句话说,您可以为每个访问者生成另一个随机顺序,但一旦为某个用户生成该顺序,该用户的顺序就需要稳定。如果您只有一个视图记录,并且不可能添加新记录,然后,您可以对所有ID使用#permutation
方法。您可以随机选择其中一个排列,并存储所选排列的索引以及此数组中的当前位置。其他明智的选择@spickermann答案。