views:

61

answers:

2

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 member 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!

+6  A: 

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

Squeegy
Sweet. Just what I was looking for.
normalocity
Is `comments` an array, or does it just quack like one?
Andrew Grimm
If it's a `named_scope` or an association it quacks like one. If you call a method that you normally call on an array it should perform the query and convert it to an array. But it doesn't do that until it needs to in case you want to add specificity to the query. The above code does not execute the SQL query until the `exists?` method is called. `comments` just returns a proxy object. But `Post.comments.each` works just like `comments` is an array.
Squeegy
+1  A: 

How did you define the relationship between 'Post' and 'Comments'? Post has_many Comments ?

If so, try .exists?().

bta