gpt4 book ai didi

ruby-on-rails - find_by_sql 不返回额外的属性

转载 作者:行者123 更新时间:2023-11-29 13:31:33 25 4
gpt4 key购买 nike

我正在使用 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。

最佳答案

我可以在 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 > List.popular.first.attributes.keys

List Load (0.2ms) select l.*, count(l.id) as popular_count from lists l group by l.id order by popular_count asc

List Load (0.1ms) SELECT "lists".* FROM "lists"

=> ["id", "name", "created_at", "updated_at"]

虽然类方法 pop 做:

2.0.0-p353 :001 > List.pop.first.attributes.keys

List Load (0.6ms) select l.*, count(l.id) as popular_count from lists l group by l.id order by popular_count asc

=> ["id", "name", "created_at", "updated_at", "popular_count"]

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

关于ruby-on-rails - find_by_sql 不返回额外的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22014589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com