【问题标题】:rails 4 how to use where and where in condition simultaneouslyrails 4如何同时使用where和where条件
【发布时间】:2013-11-23 19:44:47
【问题描述】:

我有以下问题

model = (1,2,3,4)
@posts = Post.where(category_id: id,  product_model_id: model)

我上面的查询只是从模型中获取1 我如何在这里使用where in 条件

Edit-1

这段代码有效,但我不觉得这是一个好的代码,对吧?

@posts = Post.where("category_id = ? and product_model_id in (#{model})", id)

Edit-2

如果我使用

@posts = Post.where("category_id = ? and product_model_id in (?)", id, model)

抛出错误为

invalid input syntax for integer: "15,16" 因为我的输入是这样的

select * from posts where category_id=5 and product_model_id in ('15,16')

那么如何纠正它..

【问题讨论】:

  • 代码会被注入,你不能有:ruby中的model = (1,2,3,4) 你指的是数组吗???
  • @bjhaid 请看看我的编辑

标签: ruby-on-rails activerecord ruby-on-rails-4


【解决方案1】:
model_ids = model.split(",").map(&:to_i)
@posts = Post.where(category_id: id, product_model_id: model_ids)

model_ids = model.split(",").map(&:to_i)
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model_ids)

【讨论】:

  • 你可以简单地使用user_ids = User.all.ids然后Post.where("user_id in (?)", user_ids)
【解决方案2】:

根据rails guide,你可以传入一个数组到where,它应该明白你要使用IN。请参阅此处的指南:http://guides.rubyonrails.org/active_record_querying.html#subset-conditions

我对你的语法有点困惑,因为model = (1, 2, 3, 4) 看起来不像是有效的数组语法。

指南的相关部分:

Client.where(orders_count: [1,3,5])

【讨论】:

    【解决方案3】:

    你可以使用 arel,但我会这样做:

    @posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 2021-07-12
      相关资源
      最近更新 更多