rails if object.nil? then magic '' in views?

前端 未结 8 1358
清歌不尽
清歌不尽 2020-12-23 16:46

This is one of those things, that maybe so simple I\'ll never find it because everyone else already knows it.

I\'ve got objects I have to check for nil in my views s

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 17:38

    You could write a helper method which looks like this:

    def print_if_present(var)
        var ? var : ""
    end
    

    And then use it like this (in the view):

    <%= print_if_present(your_var) %>

    If the var is nil, it just prints nothing without raising an exception.

提交回复
热议问题