从 RoR 模型中获取两个随机元素 [英] Get two random elements from a RoR model

查看:58
本文介绍了从 RoR 模型中获取两个随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 RoR 用于一些简单的事情,但在掌握基础知识时遇到了一些麻烦.我最接近的背景是 ASP.NET MVC,但我发现所有的 RoR 教程都专注于 Rails 真正擅长的东西(脚手架的东西),而不是如何制作自己的动作并让它们使用参数等(某些东西)在 ASP.NET MVC 中微不足道).

I'm trying to use RoR for something simple and I'm having some trouble picking up the basics. My closest background is ASP.NET MVC but I'm finding all of the RoR tutorials focus on what rails is really good at (scaffold stuff) but not how to make your own actions and get them to do stuff with parameters etc. (something trivial in ASP.NET MVC).

目前我正在尝试从模型中获取两个随机元素.

At the moment I am trying to get two random elements out of the model.

我想我正在处理某种 ActiveRecord 集合?

I think I'm dealing with an ActiveRecord collection of some sort?

我已经读到在集合/数组的某处有一个 .rand 方法,尽管其他地方表明 rand 只是一种获取随机数达到特定计数的方法.我什至无法让以下代码工作:

I have read that there is a .rand method somewhere on collections/arrays, although other places suggest that rand is just a method for getting a random number up to a certain count. I can't even get the following code to work:

def index
    @items = Array.new(Item[0], Item[0])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @domain }
    end
end

任何能帮助解决这个问题的东西,最好能帮助从 ASP.NET MVC 进一步修补到 RoR,我们将不胜感激.

Anything that can help with this, and ideally help with further patching from ASP.NET MVC to RoR would be really appreciated.

推荐答案

从 ActiveRecord 模型中检索两个随机项目:

To retrieve two random items from an ActiveRecord model:

@things = Thing.all(:order => 'RANDOM()', :limit => 2)

这篇关于从 RoR 模型中获取两个随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆