Ruby on rails 通过不返回额外属性的sql查找
我正在使用find_by_sql对关系进行左连接计数,如下所示:Ruby on rails 通过不返回额外属性的sql查找,ruby-on-rails,ruby,postgresql,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.updat
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\u count
?我正在使用postgres。我可以在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
类列表 查询您应该能够访问它您是对的。也许ActiveRecord在属性哈希中没有显示为属性。如果您尝试直接调用它,是否会出现错误?是的,我得到一个未定义的错误…可能是因为我试图从范围内调用find_by_sql?可能,但这会很奇怪。也许您需要一个attr_a主持人:在您的车型上流行的
。
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