[英]Active record check if attribute is in an array based on another attribute
In my Ruby on Rails project I have a Message
model which has attribute direction
as either 'incoming' or 'outgoing'. 在我的Ruby on Rails项目中,我有一个
Message
模型,其属性direction
为“传入”或“传出”。 Another attribute for Message
is body
which represents the actual content of the message. Message
另一个属性是body
,它表示Message
的实际内容。 I'm using rails 5.1.2. 我正在使用Rails 5.1.2。
Now, I want to select messages while excluding incoming messages whose body is in an array, say ['a','b','c']
. 现在,我想选择消息,同时排除正文位于数组中的传入消息,例如
['a','b','c']
。
For example, if I have the following messages in my database: 例如,如果我的数据库中包含以下消息:
{direction: 'outgoing', body: 'a'}
{direction: 'outgoing', body: 'b'}
{direction: 'outgoing', body: 'd'}
{direction: 'incoming', body: 'd'}
{direction: 'incoming', body: 'c'}
I want to only select the messages except the last one, ie {direction: 'incoming', body: 'c'}
我只希望选择除最后一条消息以外的消息,即
{direction: 'incoming', body: 'c'}
I've tried 我试过了
Message.where.not(["direction = ? and body != ?","incoming","['a','b','c']"])
This only returned me outgoing messages but the incoming message with body 'd' is missing. Message.where.not(["direction = ? and body != ?","incoming","['a','b','c']"])
这仅返回我传出的消息,但传入的消息带有主体“ d”丢失。
Any suggestions? 有什么建议么? Thanks.
谢谢。
As per the description mentioned in the post, you want to reject elements using sql on an array object. 按照文章中提到的描述,您想在数组对象上使用sql拒绝元素。
For this modify the query to accept array as an argument instead of string as mentioned in the post. 为此,修改查询以接受数组作为参数,而不是帖子中提到的字符串。
Message.where.not("direction = ? and body IN (?)","incoming",['a','b','c'])
Instead of != I think you are looking for the IN() syntax for the matches on the body. 我认为您正在寻找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>]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.