3

I am learning some Ruby on Rails, and am a newbie. Most of my background is in ASP.net MVC on the back end.

As I play with a basic scaffold project, I wonder about this case: you jump into an established Rails project and want to get to know the model. Based on what I have seen so far (again, simple scaffold), the properties for a given class are not immediately revealed. I don't see property accessors on the model classes.

I do understand that this is because of the dynamic nature of Ruby and such things are not necessary or even perhaps desirable. Convention over code, I get that. (Am familiar with dynamic concepts, mostly via JS.)

But if I am somewhere off in a view, and want to quickly know whether the (eg) Person object has a MiddleName property, how would I find that out? I don't have to go into the migrations, do I?

asked Jan 5, 2011 at 2:45
1
  • Have you tried using the rails console? Commented Jan 5, 2011 at 3:57

2 Answers 2

4

ActiveRecord provides the attributes method, which returns a hash of attribute names mapped to their values for the receiving object. So you can do something like (example console session):

> u = User.first
> u.attributes
=> {"first_name"=>"Joe", "last_name"=>"Bloggs","email"=>"[email protected]"}
> u.attributes.keys
=> ["first_name", "last_name", "email"]
> u.attributes.keys.include?("middle_name")
=> false

Documentation link

answered Jan 5, 2011 at 13:59
0

You can find the attributes of a model in schema.rb if you want the full list of attributes on a model, including association ids. Alternatively, there are many ways to do it in the console, such as pp Model.instance or puts @instance.ai, which show the same thing. However, that won't give you the methods available, since rails does a lot of work to extrapolate methods from attributes (for instance, setting a has_one :user does more than just include @instance.user).

If you want to look at your available methods on an object or model, you can use @instance.public_methods. You can subtract out inherited methods as well, e.g. @instance.public_methods - Object.public_methods or @instance.public_methods - ActiveRecord::Base.public_methods. You can also use .instance_methods on the class, for instance.

Finally, you may want to look at the annotate gem, which add comments to your models. You have to rerun it after migrations but it might be what you're looking for

answered Jun 9, 2014 at 15:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.