Rails:输出记录有更多投票的数据

时间:2015-12-07 04:34:02

标签: ruby-on-rails ruby-on-rails-4 acts-as-votable

现在我有了这个

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

但是,我有一个与旅行相关的可投票表(来自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}

我如何获得旅行才能获得ID?

编辑2

我想我想出来了......

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

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

3 个答案:

答案 0 :(得分:0)

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

类似的东西,

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

然后使用类似的东西,

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

编辑:

  

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

抱歉,错过了这一部分。宝石有一个find_liked_items方法,但不要轻易看到如何设置liked > 400之类的东西。

答案 1 :(得分:0)

昨天我回答similar question

这就是你如何以一定的票数获得旅行的身份证明(你可以使用=><=等等:

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)

答案 2 :(得分:0)

我一直试图完成评论,但是现在,我已经让这段代码发挥作用了:

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

如果其他人能想出更好的解决方案!我将标记为正确。