如何在Rails 3中的image_tag助手中执行if语句?

时间:2011-03-21 21:13:57

标签: ruby-on-rails ruby-on-rails-3

基本上我想做的是检查方法是否在对象上返回true,如果是,则将特定类应用于图像。

如果没有,那就什么都不做。

所以我尝试了这个:

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

但这是我得到的错误:

/app/views/stages/compare.html.erb:29: syntax error, unexpected ')', expecting keyword_then or ';' or '\n'
...d.upvoted? :class => 'upvoted') );@output_buffer.safe_concat...
...                               ^
/app/views/stages/compare.html.erb:31: syntax error, unexpected keyword_end, expecting ')'
');              end                        
                    ^
/app/views/stages/compare.html.erb:63: syntax error, unexpected keyword_ensure, expecting ')'
/app/views/stages/compare.html.erb:65: syntax error, unexpected keyword_end, expecting ')'

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

正如我在评论中所说,我会将确定类的逻辑移动到辅助方法:

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

然后您的图片代码帮助将是:

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