【发布时间】:2013-12-08 03:07:03
【问题描述】:
我正在 Rails 中创建一个 ActiveRecord 对象,我希望它具有只读属性。我最初尝试使用attr_readonly,但很沮丧地发现它:
- Disabled mass-updating of those properties, even on new records
- 如果记录已保存,则未引发异常,或通知您只读属性正在以任何方式更改。
我想要这两个功能;这是我的实现尝试:
# For use with ActiveRecord
module ReadOnlyAttributes
class ReadOnlyAttributeException < StandardError
end
def create_or_update # Private, but its what every method gets funneled through.
if !self.new_record? && self.respond_to?(:read_only_attributes)
changed_symbols = self.changed.map(&:to_sym)
if changed_symbols.intersect?(self.read_only_attributes)
raise ReadOnlyAttributeException, "Readonly attributes modified on #{self.class}: #{changed_symbols & self.read_only_attributes}"
end
end
super
end
end
然后在我的模型中:
class Model < ActiveRecord::Base
include ReadOnlyAttributes
def read_only_attributes
[:event_type]
end
end
是否有内置或更好的方法来获取满足上述要求的只读属性?
我对 Ruby/Rails 还是很陌生,所以我也很欣赏任何风格的 cmets。
【问题讨论】:
标签: ruby-on-rails ruby module