我正在构建一个基于PostgreSQL的rails工作板。我希望在“雇主”页面的索引中计算并显示每个雇主的职务待遇数量。这种计数的代码是什么?
我创建了一个嵌套资源,并通过以下方法关联了我的雇主和提供模型:
class Employer < ActiveRecord::Base
has_many :offers, dependent: :delete_all
end发布于 2017-01-23 11:49:01
您应该使用counter_cache,即在“雇主”表中添加一个额外的列(Offer_count)&在“提供”表中输入时更新计数器。有关详细信息,请参阅counter_cache in basics.html
你的迁徙应该喜欢
def change
add_column :employers, :offers_count, :integer, default: 0
Employer.reset_column_information
Employer.all.each do |p|
Employer.update_counters p.id, :offers_count => p.offers.length
end
endhttps://stackoverflow.com/questions/41805661
复制相似问题