I need to check if all of my Campaign
Designs
are is_validated
in my view in order to show some snippet:
Asociations
Campaign
has_many designs
Design
belongs to Campaign
Design model
scope :validated, -> { where('is_validated >= ?', true) }
My view
<% if @campaign.designs.validated %>
<i ></i>
<% else %>
<i ></i>
<% end %>
I can't get this to work. Am I missing something?
Thanks!!!
CodePudding user response:
Assuming @campaign
is an instance of the Campaign
model. The method in your view just gives you a list of validated campaigns.
You want to know if they're all validated. So turn it around and determine if a) there are more than zero campaigns, and b) if any are not validated.
It's not good practice to put this logic in the view, so in the controller, do something like this:
# app/models/campaign.rb
scope :not_validated, ->{ where(is_validated: false) }
def self.all_validated
!count.zero? && !not_validated.count.zero?
end
# campaign_controller.rb
def show
@all_validated = Campaign.all_validated
end
# show.html.erb
<% if @all_validated %>
<i ... ></i>
<% else %>
<i ... ></i>
<% end %>
but actually, it's my preference to reduce the logic in the view still further and put it in the css like this:
# the view
<i data-allValidated = <%= @all_validated %> ></i>
# the css
[data-allValidated='true']{
color: green;
}
[data-allValidated='false']{
color: red;
}