Jump to content

The ultimate community for Ruby on Rails developers.


Best method to get current user vote type for hundreds posts with Rails

active record voting postgresql

  • Please log in to reply
2 replies to this topic

#1 railrrr



  • Members
  • 2 posts

Posted 06 January 2014 - 06:34 PM

What's the best method to show user his vote type (for/against/abstain) on page with lots of post items?

direct query is

SELECT vote_type FROM votes WHERE post_id = 888 AND user_id = 888
and direct way with rails
post.votes.where(:user_id => current_user.id).pluck(:vote_type).first



but it's too heavy and stupid to make db query for every post.

I can build array of posts_id and make one query

@posts.each do |post|
ids << post.id
votes = Vote.select(:post_id, :vote_type).where(:user_id => current_user.id, :post_id => ids)SELECT post_id, vote_type FROM votes WHERE user_id = 888 AND post_id IN (887, 888, 889)

Is there built-in "magick" methods in rails? I use postgresql.

Dummy-table on pastebin

Full description on stackoverflow, does anyone can help?

#2 Ohm



  • Moderators
  • 529 posts
  • LocationCopenhagen

Posted 06 January 2014 - 07:50 PM   Best Answer

How about
votes = Post.
  joins("LEFT JOIN votes ON votes.post_id = posts.id AND votes.user_id = 1").
  select("posts.id, posts.title, users.id AS users_id, votes.vote_type")
with a
votes.map {|p| [p.id, p.title, p.users_id, p.vote_type] }
I get
[[1, "Say hello", 1, nil], [2, "Amazing world", 2, 1]]

(Same answer submitted to StackOverflow)

Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk

#3 railrrr



  • Members
  • 2 posts

Posted 06 January 2014 - 10:40 PM

Thank you, Ohm, oldschool way usually works :) I think, there is no built-in methods (like associations eg.) to make this in rails?

Also tagged with one or more of these keywords: active record, voting, postgresql

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users