gpt4 book ai didi

ruby-on-rails - 范围和实例方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:51 25 4
gpt4 key购买 nike

我有一个模型

class User < ActiveRecord::Base
has_many :articles

def good_publisher?
self.articles.size > 50
end

scope :good_publishers, -> where { ...???? }
end

如何通过 good_publisher? 表达 scope?有点像

scope :good_publishers, -> where { x.good_publisher? }

最佳答案

范围必须是 SQL 语句,最好的办法是为关联使用计数器缓存。

Article 类中,包括:

belongs_to :user, counter_cache: true # you should already have this belongs_to, all that needs to happen is include the counter_cache

然后,创建一个包含 articles_count 字段给用户的迁移:

add_column :users, :articles_count

一旦有了这个,作用域就可以写成:

scope :good_publishers, where("articles_count > 50")

关于ruby-on-rails - 范围和实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27720583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com