What is the point of object.presence?

后端 未结 5 920
太阳男子
太阳男子 2021-02-06 20:33

In the Rails docs, the example provided for the object.presence method is:

region = params[:state].presence || params[:country].presence || \'US\'
<         


        
5条回答
  •  梦毁少年i
    2021-02-06 20:47

    presence is very useful when you want to return nil if object is not present and the object itself if the object is present. In other words you want a code that looks like this:

    object.present? object : nil

    Instead of the line above you can simply call object.presence and the method will do the work for you.

提交回复
热议问题