Is an object in a given collection?
Let's say I have a blog application. On each Post there are Comments.
So, I have a collection of comments in "Post.comments"
Let's say I have an object called "this_comment"
Is there a magical keyword or construct in Ruby such that I can test "is 'this_comment' in 'Post.comments"?
In other words, I want to know if "this_comment" is a m开发者_如何转开发ember of the collection "Post.comments". I could do a 'find' and get my answer, but it seems like the kind of thing that Ruby might make easy via a cool keyword like "if this_comment.in(Post.comments)"
I suppose if not, I could just write my own "in" method for "Comment" (or 'is_in' method, as I think 'in' is a reserved keyword).
Thanks!
As an array you can do
[:a, :b, :c].include?(:a)
But ActiveRecord does some cool things to keep your queries sane if you are dealing with models. Assuming comments is a named scope or association of some sort you can do:
Post.comments.exists?(this_comment.id)
named scopes and associations can have pretty much all of the Activerecord class methods called on it
How did you define the relationship between 'Post' and 'Comments'? Post has_many Comments ?
If so, try .exists?()
.
精彩评论