Reputation: 655
I am trying to simply add an HTML class if a database value returned is a specific number. Here is what I tried:
<ul class="dog-sizes-list">
<li <%= if given_size == 1 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="30px" /></li>
<li <%= if given_size == 2 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="40px" /></li>
<li <%= if given_size == 3 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="50px" /></li>
<li <%= if given_size == 4 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="60px" /></li>
</ul>
However nothing happens and no error is produced. Furthermore, I ran the AR code in console and it returned the correct value. Specifically:
given_size = Client.where(user_id: listing.client_id).first.dogsize
What is the best approach for this?
Upvotes: 0
Views: 347
Reputation: 24815
There is no point of "active" condition because all items are active according to your code.
It seems you only want to customize the image size according to the given size. If so the better way is to define it in model, or better, in a presenter.
class Dog < ActiveRecord::Base
SIZE_AND_IMAGE = { '1': '30px', '2': '40px', '3': '50px', '4': '60px' }
# Can fallback to a default size of 30px if no size given
def image_size
given_size ? SIZE_AND_IMAGE[given_size.to_s] : '30px'
end
end
# In View
<ul class="dog-sizes-list">
<li><img src="/assets/dogs/dog-icon.png" width="#{@dog.image_size}" /></li>
Upvotes: 0
Reputation: 6501
You could get the required result in this manner:
<li class="<%= "active" if given_size == 1 %>"></li>
If you are using this kind of method regularly it would be adivsable to extract it into a helper method. The helper can be placed into your application_helper.rb file or other suitable place
def class_for_thing(thing)
if thing == whatever
"blah"
else
"not-blah"
end
Upvotes: 1