gpt4 book ai didi

ruby-on-rails - 将数据库中的随机条目显示到我的 View

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:20 25 4
gpt4 key购买 nike

所以我已经成功地建立了一个MYSQL数据库,并将一堆信息抓取到其中。我遇到的问题是我真的很难理解我想如何显示,比如从该数据库中随机输入 1 个条目到我的 View 中。我一直在阅读 MVC 和渲染,但我显然遗漏了一些东西。我想向您展示我到目前为止的内容,并希望从这里得到一些指导。我想我真的很难接受这些观点,因为它目前是空白的!

谢谢!

我的模型:

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

我的 Controller :

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

最佳答案

尝试随机排序,然后找到第一项。像这样:

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

关于ruby-on-rails - 将数据库中的随机条目显示到我的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16257620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com