Rails从同一个表查询多个参数

时间:2018-01-07 03:02:36

标签: ruby-on-rails

如何搜索多个参数?我的视图中有复选框,因此如果选中了多个复选框,我希望选择所有params。我目前只能通过以下代码使用一个param进行搜索。

has_many模型与has_many模型之间存在carcolour_collection关联。

控制器:

@cars = car.joins(:colour_collections).where("colour_collections.name = ?", params[:colour_collection])

日志显示如果选择了两种颜色(例如红色和绿色),则会在生成的查询中创建重复项:

(0.7ms)  SELECT COUNT(*) FROM "colour_collections"
  ColourCollection Load (0.5ms)  SELECT "colour_collections".* FROM "colour_collections"
  Car Load (2.5ms)  SELECT "cars".* FROM "cars" INNER JOIN "car_colour_collections" ON "car_colour_collections"."car_id" = "cars"."id" INNER JOIN "colour_collections" ON "colour_collections"."id" = "car_colour_collections"."colour_collection_id" WHERE "colour_collections"."name" IN ('Subtle', 'Intermediate') ORDER BY "cars"."created_at" DESC
  CarAttachment Load (0.5ms)  SELECT  "car_attachments".* FROM "car_attachments" WHERE "car_attachments"."car_id" = $1 ORDER BY "car_attachments"."id" ASC LIMIT $2  [["car_id", 21], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "car_attachments".* FROM "car_attachments" WHERE "car_attachments"."car_id" = $1 ORDER BY "car_attachments"."id" ASC LIMIT $2  [["car_id", 21], ["LIMIT", 1]]
  CarAttachment Load (0.5ms)  SELECT  "car_attachments".* FROM "car_attachments" WHERE "car_attachments"."car_id" = $1 ORDER BY "car_attachments"."id" ASC LIMIT $2  [["car_id", 20], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "car_attachments".* FROM "car_attachments" WHERE "car_attachments"."car_id" = $1 ORDER BY "car_attachments"."id" ASC LIMIT $2  [["car_id", 20], ["LIMIT", 1]]

4 个答案:

答案 0 :(得分:1)

如果要在单个列中搜索多个值,例如

params[:colour_collection] = ['red','green','blue'] 

然后您希望您的查询看起来像这样

SELECT * FROM cars c 
INNER JOIN colour_collections s 
WHERE s.name IN ('red','green','blue');

在这种情况下,相应的ActiveRecord语句将如下所示

Car.
joins(:colour_collections).
where(colour_collections: { name: params[:colour_collection] })

答案 1 :(得分:0)

@cars = car.joins(:colour_collections).where("colour_collections.name = ?", params[:colour_collection]).where("cars.make = ?", params[:make])

关于链接How does Rails ActiveRecord chain "where" clauses without multiple queries?

的更多讨论

答案 2 :(得分:0)

取决于您是要使用OR还是AND。有多种方法可以实现这一点,但简单的例子是

Article.where(trashed: true).where(trashed: false)
生成的sql将是
SELECT * FROM articles WHERE 'trashed' = 1 AND 'trashed' = 0

Foo.where(foo: 'bar').or.where(bar: 'bar')这是Rails 5中的常态或仅仅是 Foo.where('foo= ? OR bar= ?', 'bar', 'bar')

答案 3 :(得分:0)

Rails 5附带or方法,但Rails 4没有or方法,因此您可以在Rails 4中使用纯SQL查询。

在Rails 4中:

@cars = car.
        joins(:colour_collections).
        where("colour_collections.name = ? or colour_collections.type = ?", params[:colour_collection], params[:type])

在Rails 5中:

@cars = car.
        joins(:colour_collections).
        where("colour_collections.name = ?", params[:colour_collection]).or(car.joins(:colour_collections).where("colour_collections.type = ?", params[:type]))