I am not sure, but if what you want is to return a relation you can do this:
def self.from_microposts_voted_for_by(user)
results = find_by_sql("select m.* from microposts m
join (SELECT voteable_id, updated_at FROM votes WHERE voter_id = #{user.id} AND voteable_type = 'Micropost') z on z.voteable_id=m.id
order by z.updated_at desc")
Micropost.where id: results.map(&:id)
end
With ActiveRecord::Relation
You could build query using relations, I am not sure about your models, I will assume:
class Micropost
has_many :votes
so your method would be more coherent with Rails inside a scope:
scope(:voted_by, ->(user) do
joins(:votes).where('votes.voter_id = ?', user.id).order('votes.updated_at desc')
end)
Also you wont hit database eagerly. You would use this scope with something like this:
@microposts = Micropost.voted_by current_user