Ruby on rails 获取ActiveRecord表的更好方法&x27;s主表(属于';表)数组

Ruby on rails 获取ActiveRecord表的更好方法&x27;s主表(属于';表)数组,ruby-on-rails,ruby,activerecord,rails-activerecord,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] "

我有一张有很多字段的桌子

[
    [ 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"
]
这是不够的。因为两个几乎相同的regexp匹配得到 由于我使用了
冻结字符串

问题是:

  • Rails提供了任何方法来获取此
    所属的
    列表
  • 如果没有,有没有比我更好的解决方案? 基本上,我想要一个
    方法来满足两个条件:
    
    • 字段必须以
      \u id
    • 获取匹配的内容,但部分
      \u id
  • 谢谢。

    更好的答案是:

    GoodsItem.column_names.map {|x| x[/(.*)_id/, 1] }.compact
    
    GoodsItem.column_names.grep(/(.*)_id$/) { $1 }
    
    更好的答案是:

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

    尝试
    GoodsItem.reflections
    -GoodsItem.reflections返回
    有很多
    并且
    属于
    ,我想要的只是
    属于
    表名。你看了那页了吗
    GoodsItem。反映所有的关联(:所属)
    都能做到。@AlexandreAngelim,是的,成功了。GoodsItem.反映所有关联(:所属)。地图(&:name)得到我想要的,谢谢