Rails:输出记录得票多的数据

Rails: outputting data where record has more votes

现在我有这个

def index
  @trips = Trip.all
end

我正在输出这样的数据:

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

但是,我有一个与旅行相关的 votable table(来自 acts_as_votable gem)。我想知道我是否只能输出有一定票数的行程?

我可以这样获得选票:

- @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

编辑

如果我这样做:

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

@votes 给我这样的东西:

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

我如何获取 trip 只能获取 ID 的地方?

编辑 2

我想我明白了...

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

我得到了某种输出。有没有更好的方法?

您是否考虑过在您的 Trip 模型中使用此方法?

有点像,

def popular_trip_images
  Trip.select(:trip_images).where("likes > ?", 200)
end

然后像这样使用它,

...
trip.popular_trip_images.each do |image|
...

编辑:

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?

抱歉,错过了这一部分。 gem 有一个 find_liked_items 方法,但没有立即看到如何设置 liked > 400

昨天我回答了

这是获得一定票数的行程 ID 的方法(您可以使用 =><= 等):

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)

我一直在尝试处理评论,但现在,我已经让这段代码起作用了:

def index
  @votes = ActsAsVotable::Vote.where(votable_type: 'Trip').group(:votable_id).count
  @votes = @votes.select {|k,v| v > 1}
  @trips = Trip.where(id: @votes.keys)
end

如果有人能想出更好的解决办法!我会标记为正确的。