ARTLoe ARTLoe - 1 year ago 71
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


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

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

=> false

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

Answer Source

I would do something like this:

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

social.attendances.exists?(user: user)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download