【问题标题】:Rails where clause match integer with the arrayRails where 子句将整数与数组匹配
【发布时间】:2015-08-24 12:40:59
【问题描述】:

我在从数据库中查找正确记录时遇到问题。这是我的查询:

@interested_individual = Profile.where('category_id = ?', @event.interests).all

其中category_id 是配置文件表中保存整数值的列,@event.interests 返回一个数组,即 ["1", "2", "3"]

我想要在这里获取category_id 存在于@event.interests 数组中的所有配置文件。 请让我知道解决方案。提前致谢

【问题讨论】:

    标签: mysql ruby-on-rails arrays ruby-on-rails-4


    【解决方案1】:

    您真的不需要手动编写与? 的绑定。

    试试这个:

    @interested_individual = Profile.where(category_id: @event.interests).all
    

    如果你传入一个数组,Active Record 会为你把它变成category_id IN (?)

    【讨论】:

      【解决方案2】:

      此查询将转换为category_id IN [interest_ids...]

      Profile.where(category_id: @event.interests).all
      

      【讨论】:

        【解决方案3】:

        你很亲密。使用IN

        @interested_individual = Profile.where('category_id IN (?)', @event.interests).all
        

        但是,如果您只想收集所有 Profile 记录,我建议您在这里使用find

        @interested_individual = Profile.find(@event.interests)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-22
          • 1970-01-01
          • 2011-05-09
          • 2021-09-11
          • 2021-05-18
          • 1970-01-01
          • 2018-05-26
          相关资源
          最近更新 更多