Tom
Tom

Reputation: 9653

Ruby on Rails: find elements with value inside of a collection's array

I have a Domain model with an ips attribute that holds ip addresses:

=> #<Domain:0x005640cef7cd48> {
              :id => 1,
            :name => "example.com",
             :ips => [
        [0] #<IPAddr: IPv4:1.2.3.4/255.255.255.255>
    ]
}

And I want to find all domains which have the same ip address. So something like:

Domain.where(|d| d.ips.include? "1.2.3.4")

Is there any straight forward way to do so?

Upvotes: 1

Views: 34

Answers (1)

Pavan
Pavan

Reputation: 33542

The below query should work

Domain.where("ips @> ?", '{1.2.3.4}')

Or you can also do

Domain.where("'1.2.3.4' = ANY (ips)")

Reference

Upvotes: 1

Related Questions