置换"的has_many ... counter_sql"在Rails的4.1 [英] Replacement for "has_many ... counter_sql" in Rails 4.1
问题描述
Rails的4.1去掉了 counter_sql
从的has_many
的关联,所以下面就不再起作用:
Rails 4.1 removed the counter_sql
from has_many
associations, so the following does no longer work:
class Project < ActiveRecord::Base
has_many :backers,
-> { select('COMPLEX SQL QUERY') },
through: :pledges,
source: :backer,
counter_sql: proc { "COMPLEX COUNT SQL QUERY" }
(...)
end
我需要一个 counter_sql
在这里,因为有复杂的SQL查询选择
,AR没有建立有效的SQL时,我做的 project.backers.count
。
I need a counter_sql
here since with the COMPLEX SQL QUERY in select
, AR does not build valid SQL when I do project.backers.count
.
要解决这个问题,我想提出这个到像这样的方法:
To fix this, I'd move this to a method like so:
class Project < ActiveRecord::Base
has_many :backers,
-> { select('COMPLEX SQL QUERY') },
through: :pledges,
source: :backer
def backers_count
self.class.count_by_sql 'COMPLEX SQL QUERY'
end
(...)
end
这是一个很好的方式去还是有其他更好的办法?
Is this a good way to go or are there better approaches?
推荐答案
您可以使用关联的扩展
class Project < ActiveRecord::Base
has_many :backers,
-> { select('COMPLEX SQL QUERY') },
through: :pledges,
source: :backer do
def count
#query here
end
end
end
该协会代理可作为 proxy_association
,特别是 proxy_association.owner
返回项目对象。
The association proxy is available as proxy_association
, in particular proxy_association.owner
returns the project object.
这将覆盖默认提供的计数方法,所以 some_project.backers.count
将调用您的自定义查询
This overwrites the count method provided by default, so some_project.backers.count
will call your custom query
这篇关于置换&QUOT;的has_many ... counter_sql&QUOT;在Rails的4.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!