【发布时间】:2017-04-12 02:50:58
【问题描述】:
我有一个包含许多字段的表格
[
[ 0] "id",
[ 1] "type",
[ 2] "title",
[ 3] "delivery_fee",
[ 4] "price",
[ 5] "starting_price",
[ 6] "bid_increment",
[ 7] "bid_expired_at",
[ 8] "address",
[ 9] "lat",
[10] "lng",
[11] "comments_count",
[12] "clicks_count",
[13] "detected_labels",
[14] "deleted_at",
[15] "created_at",
[16] "updated_at",
[17] "user_id",
[18] "category_id",
[19] "area_id",
[20] "detected_labels_cn",
[21] "tsv",
[22] "tsv_full",
[23] "data",
[24] "stock_count",
[25] "location_is_visible",
[26] "make_offer_disabled_at",
[27] "favorites_count",
[28] "display_index"
]
我想做的是:
获取此表属于表名。
以下是我的解决方案:
GoodsItem.column_names.grep(/.*(_id)$/).map {|x| x[/(.*)_id/, 1]
# Or
GoodsItem.column_names.map {|x| x.dup.sub!(/_id/, '') }.compact
[
[0] "user",
[1] "category",
[2] "area"
]
这还不够。因为两个几乎相同的正则表达式匹配得到
这个结果或必须复制所有字符串,因为我使用frozen String
问题是:
- Rails 提供了任何方法来获取此
belongs_to列表? - 如果没有,有没有比我更好的解决方案来解决这个问题?
基本上,我想要一个
method满足两个条件:- 字段必须以
_id结尾 - 获取除
_id部分以外的匹配内容
- 字段必须以
谢谢。
【问题讨论】:
-
试试
GoodsItem.reflections- api.rubyonrails.org/classes/ActiveRecord/Reflection/… -
GoodsItem.reflections 返回
has_many和belongs_to,我想要的只是belongs_to表名。 -
你看过那个页面了吗?
GoodsItem.reflect_on_all_associations(:belongs_to)会做到的。 -
@AlexandreAngelim,是的,它奏效了。 GoodsItem.reflect_on_all_associations(:belongs_to).map(&:name) 得到我想要的,谢谢
标签: ruby-on-rails ruby activerecord rails-activerecord