Reputation: 5147
What is the effective way of this code?I think there should be better way.I wanna re-code this.
if @project.contest_entries.where("view_in_showcase = ?", true)
entries = @project.contest_entries.where("view_in_showcase = ?", true).count
else
entries = 1
end
Upvotes: 0
Views: 55
Reputation: 198436
showcased_project_entries =
@project.contest_entries.where("view_in_showcase = ?", true)
entries = showcased_project_entries ? showcased_project_entries.count : 1
or
entries =
@project.contest_entries.where("view_in_showcase = ?", true).try(:count) || 1
Although, I must admit I am not sure under which circumstances where
returns a falsy value.
EDIT: As noted in the comments, the else
clause indeed never triggers, so your code probably does not do what you want. See Andy H's solution for the case where you want to have entries
be 1
when you find no results, if that is what you meant.
Upvotes: 0
Reputation: 6644
You could use max
:
entries = [1, @project.contest_entries.where(view_in_showcase: true).count].max
I would define a scope on ContestEntry
to get rid of that where
clause though:
scope :showcased, where(view_in_showcase: true)
Then that would become
entries = [1, @project.contest_entries.showcased.count].max
Upvotes: 3