开发者

Is an object in a given collection?

开发者 https://www.devze.com 2022-12-20 09:58 出处:网络
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 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?().

0

精彩评论

暂无评论...
验证码 换一张
取 消