问题
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
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?
回答1:
You could use an association extension
class Project < ActiveRecord::Base
has_many :backers,
-> { select('COMPLEX SQL QUERY') },
through: :pledges,
source: :backer do
def count
#query here
end
end
end
The association proxy is available as proxy_association
, in particular proxy_association.owner
returns the project object.
This overwrites the count method provided by default, so some_project.backers.count
will call your custom query
来源:https://stackoverflow.com/questions/22988321/replacement-for-has-many-counter-sql-in-rails-4-1