开发者

How to get an array with column names of a table

I need an array with the column names of a table

Any ideas how I can do this with rail开发者_StackOverflows 3.0.0rc?


Suppose you have a Post model:

Post.column_names
# or
Post.columns.map { |column| column.name }

It will return an array with column names of the table 'posts'.


ActiveRecord::Base#column_names

create a model:

$ rails g model Post title:string body:string

verify app/models/post.rb

class Post < ActiveRecord::Base
end

from your terminal:

$ rake db:migrate
$ rails c
> Post.column_names

should produce:

=> ["id", "title", "body", "created_at", "updated_at"] 

credit to @dombesz's comment in Andrea Pavoni's answer


For ActiveRecord:

Model.column_names

For Mongoid:

Model.attribute_names

Output:

=> ["id", "title", "body", "created_at", "updated_at"] 

Note: It'll be _id instead of id for Mongoid

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜