【问题标题】:Add a method to an Object's ActiverecordRelation向对象的 ActiverecordRelation 添加方法
【发布时间】:2021-01-23 23:28:24
【问题描述】:

我有一个模型 Schoolhas_many 关系与 PerformanceStats

我发现自己经常在控制台和一些 rake 任务中编写此代码。

School.where(city: "Chicago").joins(:performance_stats).where(performance_stats: {year: "1819"}.where.not(performance_stats: {gr3_score: nil})

我也许可以通过在学校的 ActiveRecord 关系中包含一个方法来缩短此时间,所以我可以执行以下操作:

School.where(city: "Chicago").pstatjoin("1819","gr_score",nil)

def pstatjoin(year,x,y)
 x.to_sym
 self.joins(:performance_stats).where(performance_stats: {year: year}.where.not(performance_stats: {x => y})
end

但我不知道把这段代码放在哪里。

我在 SchoolsHelper 模块中试过这个:

Module SchoolHelper
  Class School
    def pstatjoin(year,x,y)
     x = x.to_sym
     self.joins(:performance_stats).where(performance_stats: {year: year}.where.not(performance_stats: {x => y})
    end
  end
end

我将模块包含在学校模型中

include SchoolsHelper

但这导致undefined method 'pj' for #<School::ActiveRecord_Relation:hexidecimal>)

有没有办法在不添加适用于每个 ActiveRecord_Relation 的代码的情况下做到这一点?

【问题讨论】:

    标签: activerecord ruby-on-rails-5


    【解决方案1】:

    我认为scopes 绝对是解决这个问题的好方法/合适的方法,使用范围可以节省一些时间并遵守 DRY 原则,因此您可以在 School 模型中定义一个范围,如下所示:

    scope :my_awesome_scope, ->(year, x, y) {joins(:performance_stats).where(performance_stats: {year: year}.where.not(x => y)}
    

    然后你可以在任何地方使用它,如下所示:

    School.my_awesome_scope(year, x.to_sym, y)
    

    甚至:School.where(...).my_awesome_scope(year, x.to_sym, y)

    希望这会有所帮助! ?

    【讨论】:

    • 完美运行,谢谢!我以前没有使用过示波器。给其他被介绍给范围的人的注意事项:当您对范围进行更改时,您必须重新启动控制台。这是工作代码: scope :my_awesome scope, ->(year, x, y) {joins(:performance_stats).where(performance_stats: {year: year}).where.not(performance_stats: {x => y} )}
    猜你喜欢
    • 2013-09-23
    • 2023-03-10
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多