0

在我的 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)

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

undefined method `limit' for #<Array:0x007f9e19806bf0>

我熟悉 Rails,但仍在学习 Ruby。任何帮助将不胜感激。

也许我也在以这种方式渲染内容<%= @related_content %>

我在用着:

  • 导轨 3.2.14
  • 红宝石 1.9.3
4

5 回答 5

7

limit is a a method on ActiveRecord relations (that adds LIMIT X) to the SQL generated. However you have an array not a relation, hence the error.

The equivalent array method is take. You can of course combine both the shuffling and the limit into one step by using the sample method

于 2013-09-20T14:45:48.547 回答
5

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

related_content.sample(3)
于 2013-09-20T14:43:10.523 回答
1

这应该有效:

related_content = []
content_sub_categories.each do |sub_cat|
  related_content << sub_cat.contents.sample(3) # add 3 random elements
end
@related_content = related_content

或者没有使用临时变量map

@related_content = @content.subcategories.map { |cat| cat.contents.sample(3) }

请注意,这@related_content是一个(3 元素)数组的数组。

于 2013-09-20T15:29:54.543 回答
0

这是查找内容 id 的子类别、所有这些子类别的内容并显示内容而不重复的最终答案:

def show
  @content = Content.includes(:author).find(params[:id])
  related_content = @content.subcategories.pluck(:id)
  @related_content = Content.joins(:subcategories).published.order('random()').limit(3).where(subcategories: { id: related_content}).where('"contents"."id" <> ?', @content.id)
end
于 2013-09-22T20:18:03.560 回答
0

这怎么样 ?

a = (1..10).to_a
p a.sample(3)
# >> [4, 10, 7]
于 2013-09-20T14:43:48.410 回答