简体   繁体   中英

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
  • i am trying to check if the user = User.find(4) is present within the attendees array

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

User.exists?(4)

Or, in a normal array object, you need the entire User object

attendees.include?(user)

or, with just the 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? :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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