1

所以我成功地建立了一个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
4

2 回答 2

2

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

Sandwich.order("RAND()").first
于 2013-04-27T23:09:04.730 回答
1

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

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

random_number = rand(Sandwich.count)
random_sandwich = Sandwich.limit(1).offset(random_number)
于 2013-04-28T12:13:06.610 回答