【问题标题】:Active record check if attribute is in an array based on another attribute活动记录检查属性是否在基于另一个属性的数组中
【发布时间】:2018-09-20 16:45:35
【问题描述】:

在我的 Ruby on Rails 项目中,我有一个 Message 模型,其属性 direction 为“传入”或“传出”。 Message 的另一个属性是body,它表示消息的实际内容。我正在使用导轨 5.1.2。

现在,我想选择消息,同时排除正文在数组中的传入消息,例如['a','b','c']

例如,如果我的数据库中有以下消息:

{direction: 'outgoing', body: 'a'}
{direction: 'outgoing', body: 'b'}
{direction: 'outgoing', body: 'd'}
{direction: 'incoming', body: 'd'}
{direction: 'incoming', body: 'c'}

我只想选择除最后一条以外的消息,即{direction: 'incoming', body: 'c'}

我试过了

Message.where.not(["direction = ? and body != ?","incoming","['a','b','c']"]) 这仅返回给我传出消息,但缺少正文为“d”的传入消息。

有什么建议吗? 谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby postgresql activerecord ruby-on-rails-5


    【解决方案1】:

    根据帖子中提到的描述,您想在数组对象上使用 sql 拒绝元素。

    为此修改查询以接受数组作为参数,而不是帖子中提到的字符串。

    Message.where.not("direction = ? and body IN (?)","incoming",['a','b','c'])
    

    【讨论】:

      【解决方案2】:

      而不是 != 我认为您正在寻找正文匹配的 IN() 语法。

         [25] pry(main)> Message.where.not("direction = ? and body in (?)", "incoming", ['a','b','c'])
        Message Load (0.3ms)  SELECT "messages".* FROM "messages" WHERE (NOT (direction = 'incoming' and body in ('a','b','c')))
      => [#<Message:0x007fee8b29a690 id: 1, direction: "outgoing", body: "a", created_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00, updated_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00>,
       #<Message:0x007fee8b29a3e8 id: 2, direction: "outgoing", body: "b", created_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00, updated_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00>,
       #<Message:0x007fee8b299fb0 id: 3, direction: "outgoing", body: "d", created_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00, updated_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00>,
       #<Message:0x007fee8b299d58 id: 4, direction: "incoming", body: "d", created_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00, updated_at: Thu, 20 Sep 2018 17:02:35 UTC +00:00>]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        • 2020-01-26
        • 1970-01-01
        • 2022-11-12
        • 2016-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多