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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With