如何建立四个随机帖子?

时间:2016-07-03 19:12:35

标签: ruby-on-rails ruby ruby-on-rails-4

我制作了以下功能正常的代码,目的是发布与显示/当前帖子不同的随机帖子。

@random_post = Post.where.not(id: @post).order("RANDOM()").first

完成此操作后,我想展示四个不同的随机帖子 因此,我将上面的代码更改为以下内容:

@random_post = Post.where.not(id: @post && @random_post).order("RANDOM()").first

不幸的是,代码输出仍然显示了四个相同的随机帖子。

2 个答案:

答案 0 :(得分:1)

Post.order("RANDOM()").limit(4)

例如:

irb(main):010:0> Post.order("RANDOM()").limit(4).map(&:id)
  Post Load (12.5ms)  SELECT  "posts".* FROM "posts"  ORDER BY RANDOM() LIMIT 4
=> ["159f0628-72af-4ec7-beed-da506a4a842a", "8a4752e4-b848-45ef-a9a3-aef40cdff8b4", "0e6b53fd-e42f-4302-9676-0b318a65202c", "2937a73b-d109-4fed-b663-68dec7e23f79"]
irb(main):011:0> Post.order("RANDOM()").limit(4).map(&:id)
  Post Load (13.6ms)  SELECT  "posts".* FROM "posts"  ORDER BY RANDOM() LIMIT 4
=> ["5b994d31-771b-4cd9-8f15-df13d6d36f6d", "7577d41e-b63f-4473-81c9-5d011ed07a76", "9c9b5c1e-f578-452a-9496-952d0e67ea19", "8e56b67e-7d2c-4fcf-a253-731e40db0f44"]
irb(main):012:0> Post.order("RANDOM()").limit(4).map(&:id)
  Post Load (14.4ms)  SELECT  "posts".* FROM "posts"  ORDER BY RANDOM() LIMIT 4
=> ["85353284-20ac-4e6f-849e-31d6d301f337", "d29cc16d-6e36-4886-ba0c-d3bd49277f2d", "524af9a3-4fe0-429f-9ab1-c1eaf31cca18", "96b4218d-e1eb-47c9-852d-237c33fdb9e9"]
irb(main):013:0> 

从问题修改的查询:

Post.where.not(id: @post).order("RANDOM()").limit(4)

例如:

irb(main):014:0> Post.where.not(id: @post).order("RANDOM()").limit(4).map(&:id)
  Post Load (13.5ms)  SELECT  "posts".* FROM "posts" WHERE ("posts"."id" != 'd29cc16d-6e36-4886-ba0c-d3bd49277f2d')  ORDER BY RANDOM() LIMIT 4
=> ["825801b9-d74d-4abe-a193-a0a55b1cf266", "b9dd32ae-b625-4a52-b41d-4167f9237057", "dd5856f4-4332-442a-aa45-f4536f549766", "476fc603-a1e3-4ee2-bb48-dc9a3ddb0dd7"]
irb(main):015:0> Post.where.not(id: @post).order("RANDOM()").limit(4).map(&:id)
  Post Load (14.2ms)  SELECT  "posts".* FROM "posts" WHERE ("posts"."id" != 'd29cc16d-6e36-4886-ba0c-d3bd49277f2d')  ORDER BY RANDOM() LIMIT 4
=> ["57897e1c-70cc-4a2d-9a5b-74bd1f28831d", "816f2580-12c0-40d1-9d9c-ed38a3eba546", "a68128fb-180f-4815-ac51-91c690d26314", "180a19bb-de77-4832-8402-d9b26d361a8c"]
irb(main):016:0> Post.where.not(id: @post).order("RANDOM()").limit(4).map(&:id)
  Post Load (13.1ms)  SELECT  "posts".* FROM "posts" WHERE ("posts"."id" != 'd29cc16d-6e36-4886-ba0c-d3bd49277f2d')  ORDER BY RANDOM() LIMIT 4
=> ["2b563cac-4312-4af5-8605-de5f918cae63", "62aaea90-3635-4dcb-9bc4-5a1b69a6b084", "119373eb-d549-4730-b70b-209c7acc4363", "d3592c65-d404-4cad-be45-17da258af7e2"]

答案 1 :(得分:0)

#Mysql  
Post.order("RAND()").first(4)

#Oracle
Post.limit(4).order("DBMS_RANDOM.VALUE")

#Postgres
Post.limit(4).order("RANDOM()")