Rails:按社交化宝石中的喜欢数量对帖子进行排序

时间:2015-03-13 08:45:20

标签: ruby-on-rails ruby

使用https://github.com/cmer/socialization允许用户喜欢帖子,我想编写一个查询来根据喜欢的数量对帖子进行排序。

这是rails c

y Like.all的结果
  Like Load (0.2ms)  SELECT "likes".* FROM "likes"
--- !ruby/object:ActiveRecord::Relation
klass: &1 !ruby/class 'Like'
table: &2 !ruby/object:Arel::Table
  name: likes
  engine: *1
  columns:
  aliases: []
  table_alias:
  primary_key:
values: {}
offsets: {}
loaded: true
should_eager_load: false
arel: !ruby/object:Arel::SelectManager
  engine: *1
  ctx: &3 !ruby/object:Arel::Nodes::SelectCore
    source: !ruby/object:Arel::Nodes::JoinSource
      left: *2
      right: []
    top:
    set_quantifier:
    projections:
    - !ruby/struct:Arel::Attributes::Attribute
      relation: *2
      name: !ruby/object:Arel::Nodes::SqlLiteral '*'
    wheres: []
    groups: []
    having:
    windows: []
  bind_values: []
  ast: !ruby/object:Arel::Nodes::SelectStatement
    cores:
    - *3
    orders: []
    limit:
    lock:
    offset:
    with:
records:
- !ruby/object:Like
  attributes:
    id: 22
    liker_type: User
    liker_id: 1
    likeable_type: Post
    likeable_id: 1
    created_at: 2015-03-07 17:08:06.133777000 Z
- !ruby/object:Like
  attributes:
    id: 23
    liker_type: User
    liker_id: 2
    likeable_type: Post
    likeable_id: 1
    created_at: 2015-03-07 17:14:40.734607000 Z
- !ruby/object:Like
  attributes:
    id: 25
    liker_type: User
    liker_id: 1
    likeable_type: Post
    likeable_id: 7
    created_at: 2015-03-08 04:59:17.948646000 Z
- !ruby/object:Like
  attributes:
    id: 26
    liker_type: User
    liker_id: 1
    likeable_type: Post
    likeable_id: 8
    created_at: 2015-03-13 08:07:18.672987000 Z
- !ruby/object:Like
  attributes:
    id: 27
    liker_type: User
    liker_id: 2
    likeable_type: Post
    likeable_id: 8
    created_at: 2015-03-13 08:07:47.133997000 Z
 => nil

likeable_id是帖子ID

由于

1 个答案:

答案 0 :(得分:2)

通过在像

这样的视图中的for循环中进行排序来解决这个问题
- @posts.sort { |a,b| b.likers(User).count <=> a.likers(User).count }.each do |post|

likers(User).count是一种社交化的宝石方式,可以让喜欢计算一个帖子。

灵感来自:https://stackoverflow.com/a/7771519/558777