模型中的一个或多个参数使用 Ruby on Rails 查找条件 [英] One or more params in model find conditions with Ruby on Rails

查看:43
本文介绍了模型中的一个或多个参数使用 Ruby on Rails 查找条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有模型Car"和控制器cars",还有一个方法display".

Say I have model 'Car' and controller 'cars', and a method 'display'.

我有多个属性,例如:

in_productionyearmake

我可以很容易地做这样的事情来找到匹配所有传递参数的汽车:

I can easily do something like this to find cars that match all the parameters passed:

def display
  @cars = Car.find(:all, :conditions => { :in_production => #{params[:in_production]}, :year => #{params[:year]}, :make => #{params[:make]} })`
end

所以我正在做的是在菜单中编码硬链接,所以如果我想找到 2009 年生产的所有 Nissan 汽车,我会将这些值作为参数传递到我的链接中.

So what I'm doing is coding hard links in the menu, so if I wanted to find all Nissan cars from 2009 that were in production, I would pass those values as parameters in my link.

在另一个页面上,我想展示 2009 年生产的每辆车,只有两个参数而不是三个.动态更改条件以便在使用相同操作的同时使用一个、两个或三个参数的最佳方法是什么?

On another page I want to show every car from 2009 that is in_production, only two params instead of three. What's the best way to dynamically alter the conditions so it will work with one, two, or three params, whilst using the same action?

有什么想法吗?

推荐答案

首先,使用

:conditions => "in_production = '#{params[:in_production]}' AND year = '#{params[:year]}' AND make = '#{params[:make]}'"

容易受到 SQL 注入的攻击.在数据库条件中使用用户提供的参数之前,您需要对其进行转义.

is vulnerable to SQL injection. You need to escape the user provided parameters before using them in database conditions.

这样的事情应该可以让您根据参数是否存在更动态地添加条件.我没有测试它,所以我可能会很快编辑它......

Something like this should let you add conditions more dynamically depending on whether or not the parameters exist. I did not test it, so I may edit it shortly...

def display
  conditions = []
  conditions << [ "in_production = ?", params[:in_production] ] if params[:in_production].present?
  conditions << [ "year = ?", params[:year] ] if params[:year].present?
  conditions << [ "make = ?", params[:make] ] if params[:make].present?
  @cars = Car.all(:conditions => conditions )
end

这篇关于模型中的一个或多个参数使用 Ruby on Rails 查找条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆