ARTLoe ARTLoe - 1 month ago 14
Ruby Question

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

Answer

I would do something like this:

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

social.attendances.exists?(user: user)