有人可以告诉我如何检查我的数组是否包含值。
attendees = social.attendances
user = User.find(4)
数组attendees
终端
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>]>
我试过以下内容:
我在终端尝试了以下但没有运气
attendees.include?(user_id:4)
=> false
attendees.include? "user_id:4"
=> false
答案 0 :(得分:2)
这些也应该有用
attendees.include?(user) #always use parentheses with methods like this
attendees.select {|a| a.id == 4}.present?
答案 1 :(得分:2)
如果您拥有模型的ID,并且想要使用SQL查询执行检查,则可以执行
User.exists?(4)
或者,在普通数组对象中,您需要整个User对象
attendees.include?(user)
或者只有id
attendees.find { |attendee| attendee.id == 4 }
答案 2 :(得分:2)
如果您只是需要检查,可以这样写:
!!attendees.find_by(user_id: 4)
#=> true or false
如果您想以Rails风格进行,可以使用present?
:
attendees.find_by(user_id: 4).present?
#=> true or false
答案 3 :(得分:1)
我会做这样的事情:
user = User.find(4)
social = Social.find(10)
social.attendances.exists?(user: user)