最简单的方法是创建一个实例方法:
#app/models/camera.rb
class Camera < ActiveRecord::Base
def color
is_online? ? "green" : "red"
end
end
这允许您拨打:
@camera.color
你可以使用一个translator,因为发现我已经不得不与custom method(否则它会非常凌乱)连接使用:
#Gemfile
gem "human_attribute_values"
#View
<%= camera.human_attribute_values(:is_online) %>
#config/locales/en.yml
en:
activerecord:
values:
camera:
is_online:
'true': "green"
'false': "red"
这是更久一点比我想象的更快,但它是实现你所需要的一种方式。
另一种选择,因为你所提到的,就是用decorators,基本上允许您创建依赖于该值的当前属性自定义属性:
#Gemfile
gem 'draper', '~> 1.3'
#app/decorators/camera_decorator.rb
class CameraDecorator < Draper::Decorator
def color
object.is_online? ? "green" : "red"
end
end
#app/controllers/cameras_controller.rb
class CamerasController < ApplicationController
def show
@camera = Camera.find(params[:id]).decorate
end
end
诚实,这可能比这样做更麻烦。