0

I'm using the devise and acts_as_votable gems to allow users to cast their votes on posts. My current objective is to query a list of the posts liked by the user.

Looking around in the Rails console I found out that when a post is voted on a votes_for table gets appended on containing information like the timestamp, vote weight and the voter_id which is what I would like to call upon.

Here's what the user controller looks like (user controller because I'm attempting to query the likes on the users/show page):

@user = current_user
@links = Link.all

@likes = @links.where.votes_for(:voter_id => @user.id) // line I'm trying to figure out, I reckon it'd look something like this

I could definitely be going about this the wrong way altogether, if that's the case I'd just appreciate some direction.

Explanation would be appreciated... I'm learning the fundamentals of Rails and finding its naming conventions convoluted and hard to follow.

JackHasaKeyboard
  • 1,599
  • 1
  • 16
  • 29

1 Answers1

1

If you're using Devise, I guess the current_user method should be available in your view and you shouldn't need a reassignment to @user

To understand how ActiveRecord works you might want to look into the documentation here.

As for the links and the voter_id, here's the way I think your query should be:

@likes = Link.where(votes_fors: {voter_id: current_user.id}) # OR Link.where(voter: current_user)

Basically the query will be transformed to a SQL query which says:

"SELECT * FROM links INNER JOIN votes_fors ON links.id = votes_fors.votable_type='Link' WHERE votes_fors.voter_id = ?" [voter_id, 1]

You get the idea?

A better approach would be to use the ActiveRecord methods to fetch these collections e.g

class User
  has_many :votes_fors, foreign_key: :voter_id
  has_many :favorites, through: :votes_fors, source: :votable # not really sure of this syntax but it should work I think.
end

With the above, you should be able to do:

current_user.favorites which would fetch you all the links voted by the user.

oreoluwa
  • 5,553
  • 2
  • 20
  • 27