问题
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