find_by_sql没有返回额外的属性

时间:2014-02-25 12:43:53

标签: ruby-on-rails ruby postgresql

我正在使用find_by_sql对类似的关系进行左连接计数:

scope :popular, lambda{ |since_date = false| 
      query = "select l.*, count(c.id) as popular_count from lists l left join choice_sets c on c.list_id = l.id and c.set_type = 'user'"
      query << "and c.updated_at > " + since_date.strftime("'%Y-%m-%d %H:%M:%S'") if since_date
      query << " group by l.id order by popular_count asc"
      find_by_sql(query)
  }

我在返回的数据方面遇到问题,不包括属性哈希中的额外属性popular_count

>  List.popular.first.attributes.keys
=> ["id", "name", "listtype", "slug", "description", "created_at", "updated_at", "user_id"] 

我相信我应该可以在此属性哈希中访问popular_count吗?我正在使用postgres。

1 个答案:

答案 0 :(得分:1)

我可以在Rails 3.2上重现这个问题(不在Rails 4上)

我在app/models/list.rb中有一个名为popular的范围和一个名为pop的类方法:

class List < ActiveRecord::Base
  scope :popular, lambda{ |since_date = false| 
    query = "select l.*, count(l.id) as popular_count from lists l "
    query << "and l.updated_at > " + since_date.strftime("'%Y-%m-%d %H:%M:%S'") if since_date
    query << " group by l.id order by popular_count asc"
    self.find_by_sql(query)
}

  def self.pop
    since_date = false
    query = "select l.*, count(l.id) as popular_count from lists l "
    query << "and l.updated_at > " + since_date.strftime("'%Y-%m-%d %H:%M:%S'") if since_date
    query << " group by l.id order by popular_count asc"
    find_by_sql(query)
  end

在控制台中,popular没有popular_count作为属性:

  

2.0.0-p353:002&gt; List.popular.first.attributes.keys

     

列表加载(0.2ms)选择l。*,count(l.id)作为popular_count从列表l group by l.id order by popular_count asc

     

列表加载(0.1ms)SELECT“列出”。* FROM“列表”

     

=&GT; [“id”,“name”,“created_at”,“updated_at”]

虽然类方法pop可以:

  

2.0.0-p353:001&gt; List.pop.first.attributes.keys

     

列表加载(0.6ms)选择l。*,计数(l.id)作为popular_count从列表l group by l.id order by popular_count asc

     

=&GT; [“id”,“name”,“created_at”,“updated_at”,“popular_count”]

因此,如果不能使用Rails 4,我建议使用类方法作为解决方法。