Ruby-on-rails 如何获取包含表列名的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3479551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an array with column names of a table
提问by Arwed
I need an array with the column names of a table
我需要一个包含表列名的数组
Any ideas how I can do this with rails 3.0.0rc?
任何想法如何使用 rails 3.0.0rc 做到这一点?
回答by Andrea Pavoni
Suppose you have a Post model:
假设你有一个 Post 模型:
Post.column_names
# or
Post.columns.map { |column| column.name }
It will return an array with column names of the table 'posts'.
它将返回一个包含表 'posts' 列名的数组。
回答by Patrick Klingemann
ActiveRecord::Base#column_names
ActiveRecord::Base#column_names
create a model:
创建模型:
$ rails g model Post title:string body:string
verify app/models/post.rb
验证应用程序/模型/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 commentin Andrea Pavoni's answer
回答by Sheharyar
For ActiveRecord:
对于 ActiveRecord:
Model.column_names
For Mongoid:
对于蒙古人:
Model.attribute_names
Output:
输出:
=> ["id", "title", "body", "created_at", "updated_at"]
Note: It'll be _idinstead of idfor Mongoid
注意:它将_id代替idMongoid

