Reputation: 383
I'm working on an approval system where an example would be filtered out if it had more negative approvals than positive.
class Set < ActiveRecord::Base
has_many :examples
end
class Example < ActiveRecord::Base
has_many :approvals, as: :approvable
end
class Approval < ActiveRecord::Base
belongs_to :approvable, polymorphic: true
belongs_to :example
attr_accessible :choice #boolean
end
I can get all approvals belonging to an Example by calling Example.approvals
.
What i'm wondering about is if it's possible to create a method on Example model that i could then use a la Example.approved
that would return true or false with a single query depending on if the example has more Approvals with true or false. Ultimately i would want to call only the examples of a set that have been approved by calling Set.approved_examples
.
Example.approved i can kind of do with
class Example < ActiveRecord::Base
...
def approved
if approvals.where(choice: true).count > approvals.where(choice: false).count
return true
end
false
end
end
although that takes two queries.
Set.approved_examples
would look like the SQL View approved_examples in here but i'm not sure where to start if i wanted a scope like this on the Set model.
Upvotes: 0
Views: 286
Reputation: 1090
Okay, based on your comment I think I misunderstood your question but maybe you coudld try something like this:
Example.all.select { |example| example.approved == true }
That would get you an array of all approved examples.
Set.first.examples.all.select { |example| example.approved == true }
That would get you an array of all approved examples that belong to the first set record.
I think there's probably a more optimal way to do this, but this does work.
Upvotes: 1