ActiveRecord查询关联模型Rails 3

我在rails中有三个模型,Project(date,has_many:project_savings),Usage(month,amount,has_many:project_savings)和MonthlyProjectSaving(amount,belongs_to:usages,:projects)。

它的设置使每个项目都有一些节省,这些节省相当于几个月的使用时间。 我试图找到所有具有相应project.date > = usage.month的项目节省,并且尽可能以最安全的方式使用usage.amount == 0usage.monthproject.date都是日期类型。

下面基本上是我想要的,但我已经尝试了很多方法,但无法正确理解语法。

在我的项目展示视图中:

 s = @project.monthly_project_savings s.where(s.usage.month >= @project.date).where(s.amount: 0) 

我更喜欢一种不会让SQL注入开放的解决方案。 干杯!

我想你可能正在寻找这样的东西,但我不确定monthly_project_savings是什么,或者用户monthly_project_savings和Project#date是什么类型。

 s.joins(:usages).where('usages.month >= ?', @project.date).where(amount: 0) 

在字符串中使用带占位符的.where非常好,因为参数会自动引用。 它是直接的SQL修改或插入不可信参数,你应该避免。 更多信息: http : //guides.rubyonrails.org/security.html#sql-injection

简而言之:在视图中进行查询并不是非常MVC; 最好是在控制器中进行,或者更好的是在模型中进行。