2011-12-09 4 views
0

初心者の質問 - 私は多態的な資産モデル(assetable_type、assetable_id)を持っています。一つのタイプは製品です。私は商品資産にのみキャプションを追加したいと思います。データベース内に問題の他の製品から作成したいキャプションフィールドはありません。私は現在、このテクニックが現在のものであるかどうかは確かではありませんが、http://blog.hasmanythrough.com/2006/4/3/polymorphic-throughで概説されている多形の反対側には興味がありません。Rails 3.1 - データベースの一部ではない属性を指定する

私はこれを思いついたが、 。

def caption 
    if self.assetable_type=='Product' 
    p=Product.find(self.assetable_id) 
    t=p.header 
    t+=" - " + p.detail unless p.detail.nil? 
    end 
    return t 
end 

このためにread_attributeを使用する方がよいでしょうか?これは属性ともみなされますか?この断片を改善するためのアイデアは高く評価されます。未テスト

答えて

0

def caption 
    @caption ||= if self.assetable_type == 'Product' 
    product = Product.find(self.assetable_id) 
    caption = product.header 
    caption + = " - " + product.detail unless product.detail.nil? 
    end 
end 
関連する問題