I need to find whether a specific attribute is present or not with where statement that takes an array in ruby.
我需要找到一个特定的属性是否存在于使用ruby中的数组的where语句。
I tried like the below.
我尝试过如下。
User.where(id: [1,2,3]).include?('address')
2 个解决方案
#1
User.where(id: [1,2,3])
would return a relation (which behaves pretty much as an array, but that's another story). It means, that is consists of objects - instances of User
class.
User.where(id:[1,2,3])会返回一个关系(它的行为几乎就像一个数组,但这是另一个故事)。这意味着,它由对象组成 - User类的实例。
You check if this collection includes string ('address'
). It is not, as you may guess by now.
您检查此集合是否包含字符串('地址')。它不是,正如你现在可能猜到的那样。
If you need to map all users by address, you can use pluck:
如果您需要按地址映射所有用户,可以使用pluck:
User.where(id: [1,2,3]).pluck(:address)
#2
You could use: User.where(id: [1,2,3]).map(&:address)
which will return an array containing the addresses.
您可以使用:User.where(id:[1,2,3])。map(&:address)将返回包含地址的数组。
And you can use User.where(id: [1,2,3]).map(&:address).map(&:present?)
if you want an array with true or false value
如果你想要一个具有true或false值的数组,你可以使用User.where(id:[1,2,3])。map(&:address).map(&:present?)
#1
User.where(id: [1,2,3])
would return a relation (which behaves pretty much as an array, but that's another story). It means, that is consists of objects - instances of User
class.
User.where(id:[1,2,3])会返回一个关系(它的行为几乎就像一个数组,但这是另一个故事)。这意味着,它由对象组成 - User类的实例。
You check if this collection includes string ('address'
). It is not, as you may guess by now.
您检查此集合是否包含字符串('地址')。它不是,正如你现在可能猜到的那样。
If you need to map all users by address, you can use pluck:
如果您需要按地址映射所有用户,可以使用pluck:
User.where(id: [1,2,3]).pluck(:address)
#2
You could use: User.where(id: [1,2,3]).map(&:address)
which will return an array containing the addresses.
您可以使用:User.where(id:[1,2,3])。map(&:address)将返回包含地址的数组。
And you can use User.where(id: [1,2,3]).map(&:address).map(&:present?)
if you want an array with true or false value
如果你想要一个具有true或false值的数组,你可以使用User.where(id:[1,2,3])。map(&:address).map(&:present?)