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

前端 未结 8 1353
清歌不尽
清歌不尽 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:42

    I've always preferred this approach:

    model:

    class TaxPayment < ActiveRecord::Base
      belongs_to :user
      delegate :name, :to=>:user, :prefix=>true, :allow_nil=>true
    end
    

    view:

    <%= tax_payment.user_name %>
    

    http://apidock.com/rails/Module/delegate

    0 讨论(0)
  • You can also try the new Object.try syntax, pardon the pun.

    This is in the shiny new Rails 2.3:

    tax_payment.try(:user).try(:name)
    
    0 讨论(0)
提交回复
热议问题