为什么数组不会随机,随机,限制等?

LMo*_*LMo 0 ruby arrays random class limit

在我的Rails控制器代码中,我想随机检索每个内容中的三个:

@content = Content.includes(:author).find(params[:id])    
content_sub_categories = @content.subcategories

related_content = []
content_sub_categories.each do |sub_cat|
  related_content << sub_cat.contents
end

@related_content = related_content.rand.limit(3)
Run Code Online (Sandbox Code Playgroud)

rand.limit(3) 不起作用,错误包括:

undefined method `limit' for #<Array:0x007f9e19806bf0>
Run Code Online (Sandbox Code Playgroud)

我熟悉Rails,但仍在学习Ruby.任何帮助都会非常感激.

也许可能是我也以这种方式呈现内容<%= @related_content %>

我正在使用:

  • Rails 3.2.14
  • Ruby 1.9.3

Fre*_*ung 7

limit是一个ActiveRecord关系的方法(添加LIMIT X)到生成的SQL.但是你有一个数组而不是关系,因此错误.

等效数组方法是take.您当然可以通过使用该sample方法将混洗和限制组合成一个步骤


Ser*_*sev 5

如果要选择3个随机元素,请使用Array#sample:

related_content.sample(3)
Run Code Online (Sandbox Code Playgroud)