【问题标题】:A better way to get ActiveRecord table's primary tables(belongs_to' tables) array获取 ActiveRecord 表的主表(belongs_to'表)数组的更好方法
【发布时间】: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

问题是:

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

谢谢。

【问题讨论】:

  • GoodsItem.reflections 返回 has_manybelongs_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


【解决方案1】:

更好的答案:

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

还有更好的答案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2016-12-28
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多