2011-10-17 4 views
0

私は2つの異なるActiveRecordに属しているRails 3 ActiveRecordを持っています。例の動物のテーブルがscientific_nameとspecies_id、zoo_id、名前、説明およびテーブル種が含まれており、動物園がアドレスを持っているActiveRecordにアクセスするには、プログラム的に含まれています

class Animal < ActiveRecord::Base 
    belongs_to: species 
    belongs_to: zoo 
... 
end 

。コントローラで

、私は、クエリ

@animals = Animal.includes(:species, :zoo).order(:name) 

と私はビューに表示する列のリスト、ビューで

@columns = ["name", "description", "species.scientific_name", "zoo.address"] 

を持って、私は、HTMLテーブルの作成をしたいです列名のリストによって駆動される

<table> 
    <tbody> 
    <tr> 
    <% @animals.each do |animal| %> 
     <% %columns.each do |col| } %> 
     <td><%= animal[</td> 
     <% end %> 
    <% end %> 
    </tr> 
    </tbody> 
</table> 

これは動物の名前と説明には効果的ですが、species.scientific_nameとzoo.addressでは機能しません。

私はループを特別に扱うことができ、animal.species ['scientific_name']のように直接インクルードされたクラスにアクセスできますが、インクルードされたクラスに名前でアクセスする方法があることを期待していました。動物のような何か[ '種'] [ 'scientific_name']

答えて

2

アプローチ1

猿のActiveRecordクラスにパッチを適用。猿のパッチを当てるARクラスの詳細についてはanswerを参照してください。

class ActiveRecord::Base 
    def read_nested(attrs) 
    attrs.split(".").reduce(self, &:send) 
    end 
end 

サンプルネストされた属性アクセス:

animal.read_nested("zoos.address") 
user.read_nested("contacts.first.credit_cards.first.name") 
product.read_nested("industry.category.name") 

ご利用の場合の場合:

コントローラー:

@columns = %w(name color zoo.address species.scientific_name) 

ビュー

<% @animals.each do |animal| %> 
    <% @columns.each do |col| } %> 
    <td><%= animal.read_nested(col)%></td> 
    <% end %> 
<% end %> 

アプローチ2

列を選択し、それらをエイリアスするselect句を追加します。あなたのビューで今すぐ

@animals = Animal.includes(:species, :zoo).select(" 
    animals.*, 
    species.scientific_name AS scientific_name, 
    zoos.address AS zoo_address"). 
    order(:name) 

、あなたは、通常のモデル属性のようなscientific_namezoo_addressなどの属性にアクセスすることができます。

+0

私が望んだほど柔軟ではありません。代わりに、私はいくつかの重要な列を正規化しました。 –

+0

@SteveWilhelm私は一般的なアプローチを追加しました。見てみましょう。 –

関連する問題