Reputation: 25
What I am trying to do is the following: Say we have a post that may have many questions and answers where both questions and answers belong to a given post. What I am trying to figure out is how to get the posts that have less than 5 questions and answers together.
something like:
@posts = Post.where(post.questions + post.answers < 5)
any suggestions?
Upvotes: 1
Views: 136
Reputation: 5993
Check out Squeel: http://erniemiller.org/projects/squeel/
Allows traversing associations, among many other things, in your query.
Upvotes: 0
Reputation: 33666
You could create a new field on the table that would hold the sum of the questions and answers of a post. This could be done using a callback like this:
class Post < ActiveRecord::Base
...
# After you've created the sum field (migration etc.)
before_save do |post|
post.sum = post.questions.count + post.answers.count
end
end
Then in your controller you could do @posts = Post.where('sum < 5')
Upvotes: 2