Ruby on Rails API:计算属性模式最佳实践

3

我希望了解在需要调用数据库的计算属性时的最佳实践。

如果我有一个拥有多个子元素ChildParent,如何在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

也许您想调整问题,如果它确实与计数器缓存有关。否则,其他解决方案适用。 - Felix
2个回答

5
在这种情况下,Rails 避免进行额外的数据库查询的方式是实现计数器缓存
为此,请更改
belongs_to :parent

child.rb中到
belongs_to :parent, counter_cache: true

在你的parents数据库表中添加一个名为children_count的整数列。当数据库中已经有记录时,你应该运行类似于以下的东西:

Parent.ids.each { |id| Parent.reset_counters(id) }

为了填充children_count,使其包含正确的现有记录数量(例如在添加新列的迁移中),您需要进行准备工作。

一旦完成这些准备工作,Rails 将自动处理增加或减少子项时的计数。

由于children_count数据库列与所有其他属性一样处理,您必须从Parent类中删除自定义的children_count方法,仍然可以简单地调用。

<%= parent.children_count %> 

在您的视图中。或者您可以将其添加到要作为JSON返回的属性列表中:
render json: parents, only: %i[attr1 attr2 children_count]

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接