【问题标题】:Get DataMapper Model Properties获取 DataMapper 模型属性
【发布时间】:2011-01-12 20:55:59
【问题描述】:

有没有办法使用 DataMapper 获取模型的属性?例如:

require 'rubygems'
require 'datamapper'

class User
  include DataMapper::Resource

  property :id, Serial
  property :name, String
end

我可以在数组或哈希中获取User 的属性吗?

【问题讨论】:

    标签: ruby datamapper


    【解决方案1】:

    是的,你可以得到它们

    User.properties
    

    它会返回一个 PropertySet 实例,如果你愿意,你可以将它转换成一个数组。

    【讨论】:

    • 这还能用吗?我在 datamapper 1.2.0 上,它似乎 .properties 现在是一个私有方法。另外,现在是require 'data_mapper'。知道获取属性的新方法是什么吗?
    • 每次我使用这个,我都会得到#的。例如我去 Blog.properties.inspect 并且它是 [#,#,#,#,#]class Blog include DataMapper::Resource property :id, Serial property :slug, String, :length => 25 property :title, String, :length => 75 property :content, Text property :created_at, Time end 试图 .to_s each 属性以及它只显示我 # 的。任何想法如何获取实际的属性名称?例如id, slug, title, content, created_at ?
    • 顺便说一句,当我说它是私有的时,这就是我所说的:github.com/datamapper/dm-core/blob/master/lib/dm-core/…
    【解决方案2】:
    >> u = User.new
    => #<User @id=nil @name=nil>
    >> u.id = 1
    => 1
    >> u.name = "hello"
    => "hello"
    >> u.attributes
    => {:name=>"hello", :id=>1}
    >> u.attributes.class
    => Hash
    

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 2015-05-03
      相关资源
      最近更新 更多