I am finding it difficult to easily see what attributes/properties exist on all of my model classes since they are not explicitly defined in my class files.
To discover model attributes, I keep the schema.rb file open and flip between it and whatever code I'm writing as needed. This works but is clunky because I have to switch between reading the schema file to pick up attributes, the model class file to check methods, and whatever new code that I'm writing to call attributes & methods.
My question is, how do you discover model attributes when you're analyzing a Rails codebase for the first time? Do you keep the schema.rb file open all the time, or is there a better way that doesn't involve jumping between schema file & model file constantly?
This question is related to
ruby-on-rails
activerecord
For Schema related stuff
Model.column_names
Model.columns_hash
Model.columns
For instance variables/attributes in an AR object
object.attribute_names
object.attribute_present?
object.attributes
For instance methods without inheritance from super class
Model.instance_methods(false)
To describe model I use following snippet
Model.columns.collect { |c| "#{c.name} (#{c.type})" }
Again this is if you are looking pretty print to describe you ActiveRecord
without you going trough migrations or hopping that developer before you was nice enough to comment in attributes.
There is a rails plugin called Annotate models, that will generate your model attributes on the top of your model files here is the link:
https://github.com/ctran/annotate_models
to keep the annotation in sync, you can write a task to re-generate annotate models after each deploy.
If you're just interested in the properties and data types from the database, you can use 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)"
Alternatively, having run rake db:create
and rake db:migrate
for your development environment, the file db/schema.rb
will contain the authoritative source for your database structure:
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
some_instance.attributes
Source: blog
Source: Stackoverflow.com