是否可以将三元运算符置于函数调用中?

时间:2014-11-06 09:50:37

标签: ruby-on-rails ternary-operator

我必须在link_to image_tag语句中处理一组条件 - 图像是否存在,用户是否拥有它?这导致了大量的代码。我想做的是这个 -

link_to image_tag(image.blank? ? generic_image : image), current_user == image.user ? edit_image_path(image) : image_path(image)

...是否可以这样做(我得到的错误只是语法问题)或者这是不可行的?

2 个答案:

答案 0 :(得分:1)

为自己制作一个自定义助手可能更容易 - 就像这样:

def link_as_image(image)
  image = generic_image if image.blank?
  path = path_for image

  link_to image_tag(image), path
end

def path_for(image)
  current_user == image.user ? edit_image_path(image) : image_path(image)
end

答案 1 :(得分:0)

有可能 - 我让这个工作:

<%= link_to image_tag((book.cover.blank? ? 'gen_book_cover.png' : book.cover), class: "bookcover"), book.user == current_user ? edit_book_path(book) : book_path(book), class: 'nolinkystyle' %>

...但上面的答案中的方法对我来说效果更好,因为在一堆地方实现它更简单。