user8331511
user8331511

Reputation:

Get complete count from database rails 5

I'm working on a dashboard where I want to get a count based on a boolean record because students can click whether they have completed a module or not, here is the boolean in the database.

database

On the dashboard I have

dash

I can get the full module count by doing this <%= CourseModule.count %> but I want to set the complete count only.

Upvotes: 0

Views: 36

Answers (1)

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

You can scope your collection with a where query:

<%= CourseModule.where(complete: true).count %>

Or to use it at multiple places, define a scope in your model CourseModule as below:

class CourseModule
  scope :completed, -> { where(complete: true) }
end

and use it everywhere as follows:

CourseModule.completed
 # => ActiveRecord Relation of completed records

CourseModule.completed.count
 # => Count of completed records

Upvotes: 1

Related Questions