Checking for nil in view in Ruby on Rails

后端 未结 5 670
故里飘歌
故里飘歌 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:10

    I personally think that if you are checking nil in your views (and I think since the view is the ultimate presentation layer nil should be checked in that level), you don't want to check it in the controller. (but this will not apply to all the places)

    I would recommend you to create a method to check nil (to make it little DRY) and pass your object and check if it is nil or not

    something like:

    def is_nil(object)
     object.nil? ? '':object 
    end 
    

    and add it in the application controller and make it a helper (so that you can use it in both controllers and views)

    (helper_method :is_nil - add this line to your application controller)

    and now you can pass the object you want to check if it is nil or not.

    cheers,

    sameera

提交回复
热议问题