简体   繁体   English

关联模型Rails 3的ActiveRecord查询

[英]ActiveRecord Query of associated model Rails 3

I have three models in rails, Project(date, has_many :project_savings), Usage(month, amount, has_many :project_savings) and MonthlyProjectSaving(amount, belongs_to :usages, :projects). 我在rails中有三个模型,Project(日期,has_many:project_ Savings),用法(月,金额,has_many:project_savings)和MonthlyProjectSaving(金额,belongs_to:usages,:projects)。

It's set up so that each project has a number of savings which correspond to a number of usages months. 设置它的目的是使每个项目都具有一定的节省量,相当于节省了数个月的使用时间。 I'm trying to find all the project savings which have a corresponding project.date >= usage.month , and also a usage.amount == 0 in the most secure way possible. 我正在尝试以最安全的方式找到所有具有相应project.date > = usage.month的项目节省,以及usage.amount == 0 usage.month and project.date are both date types. usage.monthproject.date都是日期类型。

Below is basically what I'm trying to get, but I've tried a number of ways and can't get the syntax right. 下面基本上是我要获取的内容,但是我尝试了多种方法并且无法正确获取语法。

In my project show view: 在我的项目显示视图中:

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

I'd prefer a solution which doesn't leave it open to SQL injections. 我更喜欢一个不会​​对SQL注入开放的解决方案。 Cheers! 干杯!

I think you might be looking for something like this, but I'm not sure what monthly_project_savings is, or what types Usage#month and Project#date are. 我认为您可能正在寻找类似的内容,但是我不确定什么是monthly_project_savings ,或者使用的类型是Usage#month和Project#date。

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

Using .where with placeholders in strings is perfectly fine, since the arguments are automatically quoted appropriately. 在字符串中使用带占位符的.where完全可以,因为参数会自动加引号。 It's direct SQL modification or interpolation with untrusted parameters that you should avoid. 您应避免使用直接SQL修改或使用不受信任的参数进行插值。 More information: http://guides.rubyonrails.org/security.html#sql-injection 详细信息: http : //guides.rubyonrails.org/security.html#sql-injection

Short aside: doing queries in a view isn't very MVC; 简而言之:在视图中进行查询不是非常MVC; it be better to do it in the controller or, even better, in a model. 最好在控制器中甚至在模型中做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM