Search code examples
ruby-on-railsruby-on-rails-4acts-as-votable

Rails: outputting data where record has more votes


Right now I have this

def index
  @trips = Trip.all
end

And I'm outputting data like so:

- @trips.order('created_at desc').first(4).each do |trip|
  - trip.trip_images.first(1).each do |image|
    = trip.title_name.titleize

However, I have a votable table (from acts_as_votable gem) associated to trips. I was wondering if I can only output trips where trips have a certain amount of votes?

I can get the votes like this:

- @trips.order('created_at desc').first(4).each do |trip|
  = trip.get_likes.size #this is where I can get the likes
  - trip.trip_images.first(1).each do |image|
    = trip.title_name.titleize

EDIT

If I do this instead:

def index
  @votes = ActsAsVotable::Vote.where(votable_type: 'Trip').group(:votable_id).count
  @trips = Trip.where(@votes)
end

@votes gives me something like this:

{195=>1, 106=>1, 120=>1, 227=>1, 247=>1, 264=>1, 410=>1}

How do I get it where trip will only get the ids?

EDIT 2

I think I figured it out...

def index
  @votes = ActsAsVotable::Vote.where(votable_type: 'Trip').group(:votable_id).count
  @trips = Trip.where(id: @votes.keys)
end

I got some kind of output. Is there a better way?


Solution

  • Yesterday I answered similar question.

    This is how you could get the id(s) of trip with certain amount of votes (you can use =, >, <= and so on):

    trip_ids = ActsAsVotable::Vote
      .where(votable_type: 'Trip')
      .group(:votable_id)
      .having('count(votable_id) > 1') #any number of votes
      .pluck(:votable_id)
      .uniq
    
    Trip.where(id: trip_ids)