Replacing "has_many ... counter_sql" in Rails 4.1

Rails 4.1 removed the counter_sql associations from has_many , so the following no longer works:

 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 counter_sql here, since with COMPLEX SQL QUERY in select AR does not create the correct SQL when I do project.backers.count .

To fix this, I would move this to a method like this:

 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
source share
1 answer

You can use the 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 

Association proxy server is available as proxy_association , in particular proxy_association.owner returns the project object.

This some_project.backers.count default count method provided, so some_project.backers.count will call your user request

+1
source

Source: https://habr.com/ru/post/1211361/


All Articles