【发布时间】:2020-10-09 17:59:53
【问题描述】:
当我需要一个需要调用数据库的计算属性时,我想知道最佳实践。
如果我有一个Parent 有很多Child,我将如何在ParentController#index 中渲染children_count 属性,因为我不想渲染孩子,只是计数?最好的方法是什么?
谢谢!
型号:
class Parent < ApplicationRecord
has_many :children
def children_count
children.count # Wouldn't it ask the database when I call this method?
end
end
控制器:
class ParentsController < ApplicationController
def index
parents = Parent.all
render json: parents, only: %i[attr1, attr2] # How do I pass children_count?
end
end
【问题讨论】:
-
也许你想调整这个问题,如果它真的是关于计数器缓存的。否则,适用其他解决方案。
标签: ruby-on-rails design-patterns ruby-on-rails-6