如何显示随机资源?

时间:2014-05-15 08:59:58

标签: ruby-on-rails

我的应用程序中有一个Quote模型。我在数据库中有几个引号。我想在用户刷新时在我的主页上显示Quote.all的随机引用。

我需要在控制器中放置什么才能做到这一点?

index.html.erb

<% for quote in @quotes %> ## this currently displays every quote in the databse
  <blockquote>
    "<%= "#{quote.body}" %>"
    <small><%= quote.author %></small>
  </blockquote>

这是我的报价控制器:

class QuotesController < ApplicationController
  before_action :set_quote, only: [:show, :edit, :update, :destroy]

  # GET /quotes
  # GET /quotes.json
  def index
    @quotes = Quote.all.order("created_at DESC")
  end

  # GET /quotes/1
  # GET /quotes/1.json
  def show
  end

  # GET /quotes/new
  def new
    @quote = Quote.new
  end

  # GET /quotes/1/edit
  def edit
  end

  # POST /quotes
  # POST /quotes.json
  def create
    @quote = Quote.new(quote_params)

    respond_to do |format|
      if @quote.save
        format.html { redirect_to @quote, notice: 'Quote was successfully created.' }
        format.json { render action: 'show', status: :created, location: @quote }
      else
        format.html { render action: 'new' }
        format.json { render json: @quote.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /quotes/1
  # PATCH/PUT /quotes/1.json
  def update
    respond_to do |format|
      if @quote.update(quote_params)
        format.html { redirect_to @quote, notice: 'Quote was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @quote.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /quotes/1
  # DELETE /quotes/1.json
  def destroy
    @quote.destroy
    respond_to do |format|
      format.html { redirect_to quotes_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_quote
      @quote = Quote.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def quote_params
      params.require(:quote).permit(:body, :author)
    end
end

2 个答案:

答案 0 :(得分:2)

只需获取随机Quote记录并将其分配给您可以在视图中使用的实例变量:

quote = Quote.first(offset: rand(Quote.count))

答案 1 :(得分:1)

您可以使用SQL随机顺序

@quote = Quote.order("RAND()").first