0

Given the following example code:

@user = User.last user.first_name.attr_name #this should return "first_name" 

Is there something like the "attr_name" method in Rails?

Thanks in advance

2 Answers 2

1

You could do this (but maybe ask yourself why):

user.attributes.key(user.first_name) 

...will return "first_name" as a String.

Sign up to request clarification or add additional context in comments.

4 Comments

shorter version: attributes.key(value)
WOW. I never knew about that. Thanks!
Actually user.attributes.key(user.first_name) did work for me, but attributes.key(value) not. Thanks anyway for both
value in that case refers to any arbitrary value you would enter. For example, if your user was named "John", and you ran user.attributes.key("John"), it would return "first_name".
0

To list the attributes of a model you can use column_names.

For example, User.column_names returns something like:

["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "name", "confirmation_token", "confirmed_at", "confirmation_sent_at", "account_id", "account_primary"]

You can then iterate through this array. For example, User.column_name[1] would return "email".

To view more details of each attribute, just use columns. The output of User.columns would look like this:

[#< ActiveRecord::ConnectionAdapters::Mysql2Adapter::Column:0x007fd6942b1840 @name="id", @sql_type="int(11)", @null=false, @limit=4, @precision=nil, @scale=nil, @type=:integer, @default=nil, @primary=true, @coder=nil, @collation=nil>, #< ActiveRecord::ConnectionAdapters::Mysql2Adapter::Column:0x007fd694434348 @name="email", @sql_type="varchar(255)",...

To list attributes from an instance of a model you can take MrTheWalrus's suggestion: User.first.attributes would return a hash of the first user's attributes along with their values.

Hope this is helpful.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.