How to change HTML output based on values in Rails

家住魔仙堡 提交于 2019-12-25 02:09:35

问题


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?


回答1:


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



回答2:


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>


来源:https://stackoverflow.com/questions/20210614/how-to-change-html-output-based-on-values-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!