rails 4 find_by_sql没有返回与phpPgAdmin相同的结果

时间:2013-10-05 19:59:59

标签: ruby-on-rails postgresql activerecord

当我跑

             sql = "select count( school_id ) as vote_total,
                  row_number() over( order by  count( school_id ) 
                  DESC ) as rank, school_id
                  from votes
                  where school_id = 111111
                  group by school_id"

在phpPgAdmin中,我得到了我正在寻找的东西

      vote_total rank school_id
             68    1  111111

但是当我对Vote.find_by_sql做同样的事情时,我得到了

     [#<Vote id: nil, school_id: 111111>]

我猜是find_by_sql不是我应该使用的。有关正确方法的任何想法吗?

1 个答案:

答案 0 :(得分:2)

你可以获得如下所示的vote_total和school_id

sql = "select count( school_id ) as vote_total,
                  row_number() over( order by  count( school_id ) 
                  DESC ) as rank, school_id
                  from votes
                  where school_id = 111111
                  group by school_id"

votes = Vote.find_by_sql(sql)
votes.first["vote_total"] #or votes.first.vote_total
voted.first["school_id"] #or votes.first.school_id

由于vote_total和school_id不是投票的属性,因此没有为那些人定义的getter方法