获取ActiveRecord表的主表(belongs_to'tables)数组的更好方法

时间:2017-04-12 02:50:58

标签: ruby-on-rails ruby activerecord rails-activerecord

我有一个包含许多字段的表

[
    [ 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

问题是:

  1. Rails提供了获取此belongs_to列表的任何方法吗?
  2. 如果没有,是否有更好的解决方案来解决这个问题? 基本上,我希望一个method满足两个条件:
    • 字段必须以_id
    • 结尾
    • 获取除_id
    • 部分以外的匹配内容
  3. 感谢。

1 个答案:

答案 0 :(得分:0)

更好的答案:

GoodsItem.column_names.map {|x| x[/(.*)_id/, 1] }.compact

更好的答案:

GoodsItem.column_names.grep(/(.*)_id$/) { $1 }