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匹配得到
由于我使用了冻结字符串
问题是:
所属的列表
方法来满足两个条件:
- 字段必须以
\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)得到我想要的,谢谢