Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Activerecord 将方法添加到对象';主动记录关系_Activerecord_Ruby On Rails 5 - Fatal编程技术网

Activerecord 将方法添加到对象';主动记录关系

Activerecord 将方法添加到对象';主动记录关系,activerecord,ruby-on-rails-5,Activerecord,Ruby On Rails 5,我有一个模型学校和一个学校与绩效测试有很多关系 我发现自己经常在控制台和一些rake任务中编写这些代码 School.where(city: "Chicago").joins(:performance_stats).where(performance_stats: {year: "1819"}.where.not(performance_stats: {gr3_score: nil}) 我想也许我可以通过在学校的ActiveRecord关系中加入一个方法

我有一个模型
学校
和一个
学校
绩效测试
有很多关系

我发现自己经常在控制台和一些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
但这导致了#)的
未定义方法“pj”


有没有一种方法可以在不添加适用于每个ActiveRecord\u关系的代码的情况下实现这一点?

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

scope:my_awesome_scope,->(year,x,y){join(:performance_stats.).where(performance_stats:{year:year}.where.not(x=>y)}
然后,您可以在任何地方使用它,如下所示:

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


希望这有帮助!它工作得很好,谢谢!我以前没有使用过作用域。给其他被引入作用域的人一个提示:当你对作用域进行更改时,你必须重新启动控制台。这是工作代码:作用域:my_awesome scope,->(year,x,y){joins(:performance_stats.),其中(performance_stats:{year:year}).where.not(性能统计:{x=>y})