ActiveRecord Query of associated model Rails 3

别说谁变了你拦得住时间么 提交于 2019-12-13 04:21:46

问题


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).

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. usage.month and project.date are both date types.

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. Cheers!


回答1:


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.

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. It's direct SQL modification or interpolation with untrusted parameters that you should avoid. More information: http://guides.rubyonrails.org/security.html#sql-injection

Short aside: doing queries in a view isn't very MVC; it be better to do it in the controller or, even better, in a model.



来源:https://stackoverflow.com/questions/15189361/activerecord-query-of-associated-model-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!