How do I apply one of two classes to an image depending on a certain condition in Rails 3?

僤鯓⒐⒋嵵緔 提交于 2019-12-24 20:25:49

问题


So for one class, I would do something like:

<%= image_tag(upload.image.url, :class => upload.upvoted? ? 'upvoted' : nil) %>

But I want to have it check to see if downvoted applies, and if so applies the class downvoted'. If it doesn't apply, it checks to see ifupvoted` does, and then applies that class.


回答1:


I would move the logic for determining the class to a helper method:

apps/helpers/stage_helper.rb

module StageHelper
  def upload_class(upload)
    if upload.upvoted?
      'upvoted'
    elsif upload.downvoted?
      'downvoted'
    end
  end
end

Then your image tag help would be:

<%= image_tag(upload.image.url, :class => upload_class(upload) %>


来源:https://stackoverflow.com/questions/5384369/how-do-i-apply-one-of-two-classes-to-an-image-depending-on-a-certain-condition-i

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