Replacement for “has_many … counter_sql” in Rails 4.1

此生再无相见时 提交于 2019-12-06 13:55:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!