简体   繁体   English

ActiveRecord-获取表的所有属性

[英]ActiveRecord - Getting all Attributes of a Table

I am creating a gem that has to work with any possible combination of how the attributes on a Table would be configured - the specific case I'm using it for is Feedback, so we'll use that in this example: 我正在创建一个gem,它必须与如何配置Table上的属性的任何可能组合一起工作-我使用它的具体情况是Feedback,因此在本示例中将使用它:

Given the following item: 给定以下项目:

Feedback {
  :id => 1,
  :comments => "Works well",
  :recommendations => "Change this one thing"
}

I would have to extract the data as {id: 1, comments: "Works Well", recommendations: "Change this one thing"} , which if I know the particular fields Im dealing with is a no brainer. 我必须将数据提取为{id: 1, comments: "Works Well", recommendations: "Change this one thing"} ,如果我知道Im处理的特定领域,那是不费吹灰之力的。 Unfortunately I need this to play nicely with any arrangement or collection of fields on the Feedback table. 不幸的是,我需要它与“反馈”表上的任何字段排列或集合很好地配合。

So my question is this: Does Rails or ActiveRecord have a method that will allow me to simply grab all of the fields and the relevant data in a hash / is there a way to iterate over the values of an item in the database with ActiveRecord. 所以我的问题是:Rails或ActiveRecord是否有一种方法可以让我简单地获取哈希中的所有字段和相关数据?是否有一种方法可以用ActiveRecord遍历数据库中某个项目的值。 I've tried converting the item to a Hash, using the to_params method on it, and other typical tricks for grabbing both the keys and values in key/value pairs, but to no avail. 我试过使用to_params方法将项目转换为哈希,并尝试使用其他典型技巧来同时获取键/值对中的键和值,但无济于事。

Thanks! 谢谢!

Use the attributes method. 使用属性方法。

Like Feedback.first.attributes and you are done. Feedback.first.attributes ,您就完成了。

You can use the columns_hash class method on any active_record model. 您可以在任何active_record模型上使用columns_hash类方法。

Feedback.columns_hash

or if you just need the names of the columns, use column_names 或者,如果您只需要列的名称,请使用column_names

Feedback.column_names

you can use content_columns to get only the columns that contains data, so any column, ending with _id, _count will be removed from the collection. 您可以使用content_columns仅获取包含数据的列,因此任何以_id,_count结尾的列都将从集合中删除。

Feedback.content_columns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM