Reputation: 27114
I have this in my Section
model.
scope :active, {
select: 'sections.*, COUNT(quizzes.id) as quiz_count',
joins: 'LEFT JOIN quizzes ON quizzes.section_id = sections.id',
group: 'sections.id',
having: 'quiz_count > 0',
where: 'sections.is_test = true'
}
Which works perfectly if I do not include that where
key.
But how can one append this where
clause within the statement to make it syntactically correct?
Upvotes: 0
Views: 76
Reputation: 2256
could you please post the relationships of your models in the scope?
As far as I can guess, you can try like this
scope :active, {
select: 'sections.*, COUNT(quizzes.id) as quiz_count where sections.is_test=true',
joins: 'LEFT JOIN quizzes ON quizzes.section_id = sections.id',
group: 'sections.id'
having: 'quiz_count > 0'
}
update Maybe you can use merge scope, like
scope :test, {where is_test: true},
then
Section.test.active.
I looked through the upper code, in this condition, we don't have to use the upper sql, we can just use
counter_cache: true
and the scope could be
scope :active,{where("quiz_count>?",0)}
reference: http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference
Upvotes: 1