Search code examples
postgresqlruby-on-rails-4voting

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


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
end
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.

UPD +1 same write method

current_user.votes.find_by_post_id(post.id)

UPD2 Dummy-table on pastebin


Solution

  • How about

    votes = Post.
      joins(:user).
      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]]