Checking for nil in view in Ruby on Rails

后端 未结 5 636
故里飘歌
故里飘歌 2021-01-11 09:41

I\'ve been working with Rails for a while now and one thing I find myself constantly doing is checking to see if some attribute or object is nil in my view code before I dis

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 10:01

    Don't forget .try, which was added in Rails 2.3. This means that you can call something like the following:

    @object.try(:name)
    

    And if @object is nil, nothing will be returned. This is perhaps the built-in solution for sameera207's idea.

    Ideally, you shouldn't be sending nil objects through to the view - however it's not always possible to avoid.

提交回复
热议问题