Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload with limit rails

How can one preload an association with a limit in Rails?

For example:

class Comment < ActiveRecord::Base
 belongs_to :post
end

class Post < ActiveRecord::Base
 has_many :comments
end

This works fine:

Post.all.preload(:comments)

But how I can preload only one COMMENT for each POST. (Ideally one RANDOM COMMENT for each POST)

Something like this:

Post.all.preload(:comments.limit(1))
like image 893
Serhii Danovskyi Avatar asked Sep 05 '25 21:09

Serhii Danovskyi


1 Answers

you can create custom associations below, with order as random and limit just 1 note: if you using mysql change RANDOM() to RAND()

class Post < ActiveRecord::Base
 has_many :comments
 has_one  :random_comment, -> { order("RANDOM()").limit(1) }, class_name: "Comment"
end

then you can do

Post.all.preload(:random_comment)
like image 146
widjajayd Avatar answered Sep 08 '25 11:09

widjajayd