简体   繁体   English

如何检查数组中是否存在值? -滑轨4

[英]How do I check if a value is present within my array? - Rails 4

Can one kindly advise me how i do check if my array includes a value. 请问我如何检查数组是否包含值。

  • i have an array attendees = social.attendances 我有一组attendees = social.attendances
  • i am trying to check if the user = User.find(4) is present within the attendees array 我正在尝试检查attendees数组中是否存在user = User.find(4)

Terminal 终奌站

user = User.find(4)
  User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]
 => #<User id: 4, email: "emma@gmail.com"> 


social = Social.find(10)
  Social Load (0.3ms)  SELECT  "socials".* FROM "socials" WHERE "socials"."id" = ? LIMIT 1  [["id", 10]]
 => #<Social id: 10, title: "How to successfully fundraise"> 


attendees = social.attendances
 => #<ActiveRecord::Associations::CollectionProxy [#<user_id: 10>, #<user_id: 4>, #<user_id: 14>, #<user_id: 9>, #<user_id: 6>]> 

i tried the below: 我尝试了以下内容:

i tried the below in the terminal but no luck 我在航站楼尝试了以下内容,但没有运气

 attendees.include?(user_id:4)
 => false 

attendees.include? "user_id:4"
 => false

These should work as well 这些也应该工作

attendees.include?(user) #always use parentheses with methods like this

attendees.select {|a| a.id == 4}.present?

if you have an id of your model and you want to perform a check with a SQL query you can do 如果您有模型的ID,并且想要通过SQL查询执行检查,则可以执行

User.exists?(4)

Or, in a normal array object, you need the entire User object 或者,在普通数组对象中,您需要整个User对象

attendees.include?(user)

or, with just the id 或者,仅带有ID

attendees.find { |attendee| attendee.id == 4 }

If you need just check, you can write like: 如果只需要检查,则可以这样写:

!!attendees.find_by(user_id: 4)
#=> true or false

If you want to do it in Rails-style, you can use present? 如果要以Rails样式进行操作,可以使用present? :

attendees.find_by(user_id: 4).present?
#=> true or false

I would do something like this: 我会做这样的事情:

user = User.find(4)
social = Social.find(10)

social.attendances.exists?(user: user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM