0
votes

If I have a class that belongs_to two other classes (and each of those has_many of this class), is there an easy way to find the object that belongs to both? eg.

User has_many posts

Article has_many posts

Post belongs_to User and Article

I want the post that belongs to, say, current_user and @article (there will only ever be one post belonging to both in my app)

I could figure out a way to do this but I figure there is an easy rails way to go about it.

Thanks!

2
which rails version are you using? I think you can do Post.find_by_user_id_and_article_id(current_user.id, @article.id)corroded
rails 3. I'll give this a try.Rymo4
worked perfectly! thanks! if you post as an answer i'll uprank/selectRymo4

2 Answers

1
votes

I think there are a lot of different ways, but you can do this:

Post.find_by_user_id_and_article_id(current_user.id, article.id)

or you can create your own scope to find posts

1
votes

As I said above you can do

Post.find_by_user_id_and_article_id(current_user.id, @article.id)

or you could try it with conditions as said in this answer How can I pass multiple attributes to find_or_create_by in Rails 3?

conditions = {:user_id => current_user.id,
              :article_id => @article.id}

Post.find(:conditions => conditions)

whichever floats your boat