渲染json和排序问题

时间:2013-12-03 07:03:42

标签: ruby-on-rails

以下是我的模型,为了便于阅读,我剪了一些代码:

class Meeting < ActiveRecord::Base

    def Joiners

    # Never mind , this is a complex sql, i think you do not need to read it.

    Joiners = Ploy.connection.select_all("SELECT count(users.id) as joiner FROM `ploys` INNER JOIN `participants` ON `participants`.`ploy_id` = `ploys`.`id` INNER JOIN `users` ON `users`.`id` = `participants`.`user_id` where `participants`.`ploy_id`= #{self.id}")
    Joiners.rows[0][0]

    end

    def as_json(options={})
        super(methods: :Joiners)
    end

如果我使用

render json: @Meeting

它将使用 Joiners 属性呈现JSON。

{
  "Meeting":{
   ...

   "Joiners":15,

   ...
  }

  "Meeting":{
   ...

   "Joiners":13,

   ...
  }

}

所以:

  

我如何按加入者排序?

由于

1 个答案:

答案 0 :(得分:0)

您必须使用SQL ORDER BY

在查询结果中对其进行排序