0

I have a Post model and a Comment model; Post has_many comments, and Comment belongs_to Post

In my Post controller, I want to select a random comment, and display the comment's date. I'm a little confused how to query this from my Post controller.

In my Post Controller, I have:

@posts = Post.where(:public_flag => true).order('created_at DESC')

I'm a little stuck after this. Should I be getting the comments from the view? Or doing another query from the controller to get the comments? Then, how do I just select a random comment once I get all the comments?

Thanks in advance! Really appreciate your help.

gitastic
  • 516
  • 7
  • 26
  • _random_ comment per post ? – Arup Rakshit Nov 04 '14 at 17:48
  • Not necessarily per post - I just want to get a random comment from all comments, but then I need to know which post it came from – gitastic Nov 04 '14 at 17:50
  • `Comment.all.sample.post` will do the job. – Arup Rakshit Nov 04 '14 at 17:51
  • thanks arup! That worked. But, what does the ".post" do, because I just put Comment.all.sample, and I get a random sample of comments. Also - how would I get a different random samples if I want to display multiple random comments? In my controller I have random_comment = Comment.all.sample. So, in my view, if I have random_comment, it only displays 1 comment. – gitastic Nov 04 '14 at 17:54
  • `.post` will give you which post's comment it is.. – Arup Rakshit Nov 04 '14 at 17:55
  • how do i call that post in the view? sorry for all the questions! – gitastic Nov 04 '14 at 17:56
  • `@comment = Comment.all.sample`.. Now use `@comment` in your view like `@comment.post`.. – Arup Rakshit Nov 04 '14 at 18:08

2 Answers2

1

Applying this answer to your question:

offset = rand(@post.comments.count)

# Rails 4
rand_record = @post.comments.offset(offset).first

# Rails 3
rand_record = @post.comments.first(:offset => offset)

I hope it helps

Community
  • 1
  • 1
Alejandro Babio
  • 5,189
  • 17
  • 28
0

Now sure what purpose will showing random comment serve for your case. However, you can do this in your controller:

@posts = Post.includes(:comments).where(:public_flag => true).order('created_at DESC')

then in view:

<% @posts.each do |post| %>
  Post title: <%= post.title %>
  <%= post.comments.sample.created_at # will show a random comment's created_at date per post %>
<% end %>

Read this to know what sample does.

Surya
  • 15,703
  • 3
  • 51
  • 74
  • thanks for this! I can't seem to get it to work though. I added all your code, and it says 'undefined method 'create_at'. I tried it with other fields too, i.e., id, comment, etc., and it is all undefined method for nil:NilClass – gitastic Nov 04 '14 at 18:43
  • @gitastic : Actually, that was an example. And I am sorry that I mistyped `create_at`, it should be `created_at`, please see the updated revision. – Surya Nov 04 '14 at 18:45