I would like to know the best practice when I need a computed attribute that require a call to the database.
If I have a Parent
that has many Child
, how would I render a children_count
attribute in ParentController#index
as I don't want to render the children, just the count? what's the best way to do it?
Thank you!
Model:
class Parent < ApplicationRecord
has_many :children
def children_count
children.count # Wouldn't it ask the database when I call this method?
end
end
Controller:
class ParentsController < ApplicationController
def index
parents = Parent.all
render json: parents, only: %i[attr1, attr2] # How do I pass children_count?
end
end
Aucun commentaire:
Enregistrer un commentaire