【发布时间】:2010-12-16 23:02:53
【问题描述】:
我有一个关于 ActiveRecord 的问题,希望你们能帮助我。在此先感谢:)。
我有一个 ActiveRecord 模型,它有一个布尔字段来指示用户是否已接受许可。我不想创建与此相关的数据库列,但我希望它使用 ActiveRecord 提供的所有验证内容和类型转换。网上有很多解决方案,但都专注于无表模型(例如,http://railscasts.com/episodes/193-tableless-model),而我的模型也有其他与表格列对应的字段。这是我想出的:
class User < ActiveRecord::Base
include TablelessColumns
tableless_column :license_accepted, :boolean
# other fields that are corresponding to table columns
end
module TablelessColumns
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def tableless_columns
read_inheritable_attribute(:tableless_columns)
end
def tableless_column(name, sql_type = nil, default = nil, null = true)
write_inheritable_attribute(:tableless_columns, {}) if tableless_columns.nil?
tableless_columns[name] = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
define_method("#{name.to_s}=".to_sym) { |value| instance_variable_set(to_variable(name), value) }
define_method(name) { self.class.tableless_columns[name].type_cast(instance_variable_get(to_variable(name))) }
end
end
def to_variable(sym)
"@#{sym.to_s}".to_sym
end
end
这个解决方案看起来很冗长,我想知道是否有更好的解决方案。
【问题讨论】:
标签: ruby-on-rails activerecord