Ruby-on-rails rails 4 如何同时使用 where 和 where 条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20167020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails 4 how to use where and where in condition simultaneously
提问by overflow
I have the following query
我有以下查询
model = (1,2,3,4)
@posts = Post.where(category_id: id, product_model_id: model)
My above query is justing taking the 1from model how can i use where incondition over here
我上面的查询只是采用1from 模型我如何where in在这里使用条件
Edit-1
编辑-1
This piece of code works but I don't feel this as a good code right?
这段代码有效,但我觉得这不是一个好的代码,对吗?
@posts = Post.where("category_id = ? and product_model_id in (#{model})", id)
Edit-2
编辑-2
If I use
如果我使用
@posts = Post.where("category_id = ? and product_model_id in (?)", id, model)
@posts = Post.where("category_id = ? and product_model_id in (?)", id, model)
Throwing error as
抛出错误为
invalid input syntax for integer: "15,16"because my input is like this
invalid input syntax for integer: "15,16"因为我的输入是这样的
select * from posts where category_id=5 and product_model_id in ('15,16')
select * from posts where category_id=5 and product_model_id in ('15,16')
How to correct it then..
那怎么改。。
回答by bjhaid
model_ids = model.split(",").map(&:to_i)
@posts = Post.where(category_id: id, product_model_id: model_ids)</code>
or
或者
model_ids = model.split(",").map(&:to_i)
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model_ids)
回答by Max
According to the rails guide, you can pass in an array to whereand it should understand that you want to use IN. See the guide here: http://guides.rubyonrails.org/active_record_querying.html#subset-conditions
根据rails指南,您可以将数组传递给where它,它应该明白您要使用IN。请参阅此处的指南:http: //guides.rubyonrails.org/active_record_querying.html#subset-conditions
I'm a little confused by your syntax, since model = (1, 2, 3, 4)doesn't look like valid array syntax.
我对你的语法有点困惑,因为model = (1, 2, 3, 4)它看起来不像有效的数组语法。
Relevant part of the guide:
指南的相关部分:
Client.where(orders_count: [1,3,5])
回答by CDub
You could use arel, but I'd just do something like:
你可以使用arel,但我只会做类似的事情:
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model)
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model)

