2017-04-12 10 views
0

私は私が何をしたいのか、多くの分野(」テーブルbelongs_toの)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" 
] 

これは十分に商品はありません:

以下は私のソリューションです。 2つのほぼ同じ正規表現マッチは この結果を取得したり、すべての文字列をDUPする持っているので、私はfrozen String

を使用するための質問です:

  1. Railsはこのbelongs_toリストを取得するために任意のメソッドを提供しますか?
  2. そうでない場合は、私よりも解決するためのより良い解決策がありますか?一部_id

おかげ除き一致コンテンツを取得

  • フィールドが_id
  • で終わる必要があります: は基本的に、私は1つmethodが2つの条件を満たすようにしたいです。

+0

'GoodsItem.reflections'をお試しください - http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods .html –

+0

GoodsItem.reflectionsは、 '' has_many''と '' belongs_to''を返します。ちょうど '' belongs_to''のテーブル名が必要です。 – zw963

+0

あなたはそのページを見ましたか? 'GoodsItem.reflect_on_all_associations(:belongs_to)'がそれを行います。 –

答えて

0

良い答え:

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

そして、もっと良い答え:

GoodsItem.column_names.grep(/(.*)_id$/) { $1 } 
関連する問題