代码之家  ›  专栏  ›  技术社区  ›  gbc

如何在Rails中发现模型属性?

  •  127
  • gbc  · 技术社区  · 17 年前

    我发现很难很容易地看到我的所有模型类上都存在哪些属性/属性,因为它们在我的类文件中没有明确定义。

    为了发现模型属性,我将schema.rb文件保持打开状态,并根据需要在它和我正在编写的任何代码之间切换。这是可行的,但很笨拙,因为我必须在读取模式文件以获取属性、检查方法的模型类文件以及我正在编写以调用属性和方法的任何新代码之间切换。

    我的问题是,当您第一次分析Rails代码库时,如何发现模型属性?您是一直打开schema.rb文件,还是有更好的方法不需要经常在模式文件和模型文件之间切换?

    5 回复  |  直到 8 年前
        1
  •  253
  •   Ian Vaughan    13 年前

    用于架构相关的内容

    Model.column_names         
    Model.columns_hash         
    Model.columns 
    

    例如,ar对象中的变量/属性

    object.attribute_names                    
    object.attribute_present?          
    object.attributes
    

    例如,没有从超级类继承的方法

    Model.instance_methods(false)
    
        2
  •  25
  •   Deekor    10 年前

    有一个叫做注释模型的Rails插件,它将在模型文件的顶部生成模型属性。 链接如下:

    https://github.com/ctran/annotate_models

    为了保持注释同步,可以编写一个任务,以便在每次部署后重新生成注释模型。

        3
  •  11
  •   Nick    13 年前

    如果您只对数据库中的属性和数据类型感兴趣,可以使用 Model.inspect .

    irb(main):001:0> User.inspect
    => "User(id: integer, email: string, encrypted_password: string,
     reset_password_token: string, reset_password_sent_at: datetime,
     remember_created_at: datetime, sign_in_count: integer,
     current_sign_in_at: datetime, last_sign_in_at: datetime,
     current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
     updated_at: datetime)"
    

    或者,跑步 rake db:create rake db:migrate 对于您的开发环境,文件 db/schema.rb 将包含数据库结构的权威源:

    ActiveRecord::Schema.define(version: 20130712162401) do
      create_table "users", force: true do |t|
        t.string   "email",                  default: "", null: false
        t.string   "encrypted_password",     default: "", null: false
        t.string   "reset_password_token"
        t.datetime "reset_password_sent_at"
        t.datetime "remember_created_at"
        t.integer  "sign_in_count",          default: 0
        t.datetime "current_sign_in_at"
        t.datetime "last_sign_in_at"
        t.string   "current_sign_in_ip"
        t.string   "last_sign_in_ip"
        t.datetime "created_at"
        t.datetime "updated_at"
      end
    end
    
        4
  •  9
  •   Haris Krajina    13 年前

    为了描述模型,我使用以下代码片段

    Model.columns.collect { |c| "#{c.name} (#{c.type})" }
    

    同样,如果你想用漂亮的印刷体来描述你的话 ActiveRecord 在你对属性有足够好的评价之前,你不需要经历迁移或者跳过开发人员。

        5
  •  4
  •   Marius Butuc Alec Hartman    11 年前
    some_instance.attributes
    

    来源: blog

    推荐文章