How to implement Yes/No instead of Boolean for certain cases in Rails?

前端 未结 3 566
庸人自扰
庸人自扰 2021-01-02 21:47

I\'m a newb at programming but in my application I want certain cases to display \"yes\" or \"no\" instead of \"true\" or \"false\". I\'m not sure the best way to do this,

3条回答
  •  被撕碎了的回忆
    2021-01-02 22:21

    Assuming you have :boolean attribute in your model/database, you can do this:

    class Foo < ActiveRecord::Base
      def bar
        self[:bar] ? 'Yes' : 'No'
      end
    end
    

    The whenever you want the "Yes"/"No" value, call @foo.bar. Whenever you want the true/false value, call @foo.bar? or @foo[:bar].

提交回复
热议问题