Ghamtre Ghamtre - 5 months ago 6
Ruby Question

How to establish four random posts?

I made the following properly functioning code with the purpose of posting a random post different from the displayed/current post.

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


Having accomplished this, I would like to display four distinct random posts.

Hence, I change the code above to the following:

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


Unfortunately, the code output still shows four of the same random posts.

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

For example:

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> 

Query modified from question:

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

For example:

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"]
Comments