【问题标题】:thumbs_up gem to sort liked posted - railsthumbs_up gem 对喜欢的帖子进行排序 - rails
【发布时间】:2013-10-08 08:00:05
【问题描述】:

我正在使用 thumbs_up gem 让用户喜欢设计和产品。在用户个人资料中,我让它显示了用户喜欢的所有设计和产品。现在,我已将设计和产品连接到一个视图中,但它们是为设计+产品订购的“created_at DESC”。我想根据用户投票的时间来订购它,所以当用户对设计投票时,它首先出现在他们的个人资料上。这是我的代码

在模型中

def favorites
  Design.joins(:votes).where('voter_id = ?', self.id).where('voteable_type = ?', 'Design').where('vote = ?', true)
end

def favs
  Product.joins(:votes).where('voter_id = ?', self.id).where('voteable_type = ?', 'Product').where('vote = ?', true)
end

在控制器中

@user = User.find_by_username(params[:id])
@designs = @user.favorites
@products = @user.favs

@favorites = @designs.to_a.concat @products.to_a
@favorites.sort! {|t1, t2| t2.created_at <=> t1.created_at}

我什至删除了设计和产品的默认范围,以防出现问题但它没有解决它。

我也试过了,没有运气

Design.joins(:votes).where('voter_id = ?', self.id).where('voteable_type = ?', 'Design').where('vote = ?', true).order('created_at DESC')

每个投票都有一个时间戳“created_at”。所以我知道这是可能的。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    如果用户has_many :votes,投票belong_to :voteable 并且每个用户只对特定的voteable 投票一次,我会尝试这样的事情:

    @user.votes.includes(:voteable).order('created_at DESC')
    

    这将返回按创建日期排序的选票集合。然后您可以遍历它们并根据需要显示它们的voteable 属性。如果您只想要设计而不是产品,那么您需要加入而不是 includes 并按 voteable_type 过滤

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-25
      • 2017-06-15
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      相关资源
      最近更新 更多