我有以下型号:
class ActivityLog < ActiveRecord::Base
validates :user_id, :instance_id, :action, presence: true
validates :user_id, :instance_id, :action, numericality: true
belongs_to :user
def self.log(action, instance)
ActivityLog.create(
user_id: instance.user.id,
instance_id: instance.id,
action: action
)
end
def action
actions[:action]
end
def action=(action)
write_attribute(:action, actions.index(action))
end
def actions
['start','stop','create','destroy']
end
end
我试图在模块的接口层中替换def actions
中定义的关键字,但在数据库中保存一个整数。
我有以下问题:
def actions
我认为应该在课堂上定义,但我不确定如何从实例中调用它。private
中的内容应该是什么?答案 0 :(得分:1)
这样做的标准方法是使用常量:
class ActivityLog < ActiveRecord::Base
validates :user_id, :instance_id, :action, presence: true
validates :user_id, :instance_id, :action, numericality: true
belongs_to :user
enum action: ['start','stop','create','destroy']
def self.log(action, instance)
ActivityLog.create(
user_id: instance.user.id,
instance_id: instance.id,
action: action
)
end
end
ActivityLog.actions #=> ['start','stop','create','destroy']
a = ActivityLog.new
a.status = 'start'
a.status #=> 'start'
a.start? #=> true
如果您正在运行rails 4.1,则可以使用{{1}}:
{{1}}