当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - 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 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!

网友答案:

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?().

分享给朋友:
您可能感兴趣的文章:
随机阅读: