Rails Collection#exists?
I've been using Rails for almost a decade, and find I still don't know even close to all it has to offer. Today, I was browsing through an open source app, and stumbled across this code:
unless feed.posts.exists?(@post.id)
feed.posts << @post
end
I'd never seen or used exists?
on a collection before, so I looked it up. And of course, there it is, right in the Rails Guides Association Basics - methods added by has many!
Digging in a bit, what arguments can exists?
take? Here's the reference.
Turns out there a lot of options!. Integer, string, array, hash, false
, or no args.
Well that's kinda neat! So what does the no args do?
It seems to behave similar to any?
, and return true if there are any members of the collection, false if it's empty.
TLDR: Read the Rails Guides. A decade in, you'll probably still learn something!
Tweet