获得类型的属性在一个ActiveRecord对象
-
25-09-2019 - |
题
我想知道是否有可能得到类型(如AR知 - 例如,在迁移脚本和数据库)编程(我知道在那里的某个地方数据存在)。
例如,我可以处理所有属性名称:
ar.attribute_names.each { |name| puts name }
.attributes仅返回名称与其当前值的映射(例如,如果字段未设置任何类型的信息)。
我已经与所述类型信息看出它的一些地方:
在脚本/控制台,键入的AR实体的名称:
>> Driver
=> Driver(id: integer, name: string, created_at: datetime, updated_at: datetime)
因此清楚地知悉的类型。此外,还有.column_for_attribute,这需要生成的attr名称,并返回一个列对象 - 其中有埋在底层数据库列对象的类型,但它并不似乎是一个干净的方式得到它。
我也有兴趣,如果有一种方式,是新的“加载ActiveModel”,也就是未来的(Rails3中)友好和从数据库细节分离(但也许键入的信息将不会成为其中的一部分,我可以”不像是会看看它是)。
感谢。
解决方案
在Rails 3中,为你的模型 “驱动程序”,你想Driver.columns_hash
。
Driver.columns_hash["name"].type #returns :string
如果您通过他们想迭代,你会做这样的事情:
Driver.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}
这将输出以下内容:
id => integer
name => string
created_at => datetime
updated_at => datetime
其他提示
可以通过这样做访问类型列的:
#script/console
Driver.columns.each {|c| puts c.type}
如果你想在某一特定型号的所有列类型的列表,你可以这样做:
Driver.columns.map(&:type) #gets them all
Driver.columns.map(&:type).uniq #gets the unique ones
在导轨5,则可以独立于数据库的做到这一点。如果你使用新属性的API定义(额外)的属性是非常重要的。
获取所有属性从一个模型类:
pry> User.attribute_names
=> ["id",
"firstname",
"lastname",
"created_at",
"updated_at",
"email",...
获取类型:
pry> User.type_for_attribute('email')
=> #<ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x007ffbab107698
@limit=255,
@precision=nil,
@scale=nil>
这有时比需要更多的信息。还有,所有这些类型映射至一组核心便利功能(:整数,:字符串等)
> User.type_for_attribute('email').type
=> :string
您还可以得到所有在一个呼叫与attribute_types数据返回一个'name': type
哈希值。
在轨道5,这将让你与他们的数据类型以及所有域名的列表:
Model_Name.attribute_names.each do |k| puts "#{k} = #{Model_Name.type_for_attribute(k).type}" end
这个片段将让你与哈希相关的数据库中的数据类型的模型的所有属性。只需用Active Record的型号更换后。
Post.attribute_names.map {|n| [n.to_sym,Post.type_for_attribute(n).type]}.to_h
将返回一个散列这样。
=> {:id=>:integer, :title=>:string, :body=>:text, :created_at=>:datetime, :updated_at=>:datetime, :topic_id=>:integer, :user_id=>:integer}
不隶属于 StackOverflow