在不访问单个父记录的情况下获取随机子记录 - Rails 4

Get random child record without accessing individual parent record - Rails 4

我正在创建一个测验之类的网站。

我有类别、问题和选​​择作为表格。

我想要的是,在我列出我的类别的地方,当我点击类别时,我希望它将我带到 categories/1/questions/< 随机问题> 路径.

关系成立

这是我目前的情况。

index.erb.html(类别)

    <ul class="categories-list">
      <% @categories.each do |category| %>
        <% if category.header %>
        <% @count = @count + 1 %>
          <li class="panel header" id="cat<%= @count %>">
            <a href="#"><%= category.title %></a>
            <small>781 of 781 questions remaining</small>
          </li>
        <% else %>
          <li class="panel sub hidden subcat<%= @count %>" >
            <%= link_to category.title, category_question_path(category,category.questions.limit(1).order("RAND()")) %>
            <small>781 of 781 questions remaining</small>
          </li>
        <% end %>

      <% end %>
    </ul>

类别-controller.rb

  def index
    @count = 0
    @categories = Category.order(:tag)

  end

执行此操作的最通用方法(独立于数据库供应商):

category.questions.offset(rand(category.questions.count)).first

供应商特定查询也是可能的:

category.questions.order("RANDOM()").first # postgres
category.questions.order("RAND()").first # mysql

定义新动作/random_question:

def random_question
  category = Category.find params[:category_id]
  question = category.questions.offset(rand(category.questions.count)).first
  redirect_to question_path(question)
end