在数据库中显示随机条目到我的视图

时间:2013-04-27 22:45:08

标签: ruby-on-rails ruby

所以我成功构建了一个MYSQL数据库并将大量信息写入其中。我遇到的问题是我真的很难理解我想如何显示说法,从该数据库中随机输入1到我的视图中。我一直在阅读MVC和渲染,但我显然遗漏了一些东西。我想告诉你我到目前为止所做的事情,希望能从这里得到一些指示。我认为我真的很挣扎于这些观点,因为它目前是空白的!

谢谢!

我的模特:

class Sandwich < ActiveRecord::Base
  attr_accessible :country, :description, :image, :name
  def self.random_sandwich
Sandwich.find(:first, :order => "RAND()")
  end
end

我的控制器:

class SandwichesController < ApplicationController
  # GET /sandwiches
  # GET /sandwiches.json
  def index
    @sandwich = Sandwich.random_sandwich

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @sandwiches }
    end
  end

  # GET /sandwiches/1
  # GET /sandwiches/1.json
  def show
    @sandwich = Sandwich.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @sandwich }
    end
  end

  # GET /sandwiches/new
  # GET /sandwiches/new.json
  def new
    @sandwich = Sandwich.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @sandwich }
    end
  end

  # GET /sandwiches/1/edit
  def edit
    @sandwich = Sandwich.find(params[:id])
  end

  # POST /sandwiches
  # POST /sandwiches.json
  def create
    @sandwich = Sandwich.new(params[:sandwich])

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

  # PUT /sandwiches/1
  # PUT /sandwiches/1.json
  def update
    @sandwich = Sandwich.find(params[:id])

    respond_to do |format|
      if @sandwich.update_attributes(params[:sandwich])
        format.html { redirect_to @sandwich, notice: 'Sandwich was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @sandwich.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /sandwiches/1
  # DELETE /sandwiches/1.json
  def destroy
    @sandwich = Sandwich.find(params[:id])
    @sandwich.destroy

    respond_to do |format|
      format.html { redirect_to sandwiches_url }
      format.json { head :no_content }
    end
  end
end

2 个答案:

答案 0 :(得分:2)

尝试随机订购,然后找到第一项。 像这样的Smth:

Sandwich.order("RAND()").first

答案 1 :(得分:1)

我认为会慢一些。因为它随机化所有数据并选择第一个数据。

还有另一种方法。生成0到总三明治之间的随机数 - 1.使用该数字作为偏移量来获得随机三明治。

random_number = rand(Sandwich.count)
random_sandwich = Sandwich.limit(1).offset(random_number)