2016-04-04 12 views
0

は、我々は@apple.fruit.tree.organismを呼び出すすることを避けるために、この不自然なモデル構造ネストされたhas_one関連付けを定義する方法は?

class Apple < ActiveRecord::Base 
    belongs_to :fruit 
    has_one :tree, through: :fruit 
    has_one :organism, through: :tree 
end 

class Fruit < ActiveRecord::Base 
    belongs_to :tree 
    has_many :apples  
end 

class Tree < ActiveRecord::Base 
    belongs_to :organism 
    has_many :fruits 
end 

class Organism < ActiveRecord::Base 
    has_many :trees 
end 

があると、私はアップルの2 has_oneのスルーディレクティブをdefinded、そして@apple.organismが動作することを期待しますが、それはしていませんしています。 @apple.tree.organismは機能しません。

何か間違っていますか?私はちょうどゲッターメソッドを定義する必要があります:アップルのインスタンス上の生物とそれで完了?

+0

これは正常に動作しますが、エラーメッセージは何ですか? –

答えて

0

has_oneは、技術的にはbelongs_toの特性を実行します:生物と考えてくださいhas_manyりんごthrough木以外ではありません。 "belongs_to:through"はRailsでは動作しませんので、お使いのモデルでdelegateを使用することをお勧めします。

class Apple < ActiveRecord::Base 
    delegate :organism, to: :fruit 
end 

class Fruit < ActiveRecord::Base 
    delegate :organism, to :tree  
end 
+0

私は1つのレベル:through(.treeを取得する)とAppleのdelegate(delegate:生物、to::tree)を組み合わせてしまいました。 – Epigene

関連する問題