2015-10-30 319 views
0

查詢HAS_ONE模型我有兩個型號:具有特定屬性值

class Tree < ActiveRecord::Base             
    has_many :leafs                
    has_one :latest_leaf, -> { order(created_at: :desc) }, class_name: "Leaf"  

    def self.with_connected_latest_leafs           

    end                   
end 

class Leaf < ActiveRecord::Base             
    belongs_to :tree                
end                    

class CreateTrees < ActiveRecord::Migration          
    def change                  
    create_table :trees do |t|             
     t.timestamps                
    end                   
    end                   
end 

class CreateLeafs < ActiveRecord::Migration          
    def change                  
    create_table :leafs do |t|             
     t.integer :tree_id               
     t.string :state               
     t.timestamps                
    end                   
    end                   
end                    

我希望所有樹木的列表,以latest_leaf具有「連接」的狀態。

回答

0

如果您使用Rails 4,你可以使用這個:

Three.joins(:leafs).where(latest_leaf: { state: "connected" }) 
+0

我得到這個錯誤: 'PG :: UndefinedTable:錯誤:缺少表「latest_leaf」的FROM子句項' – AndrewVos

+0

我的錯誤。 'joins'命令中的參數應該是'Leaf'模型的表名(我想它是'leafs') –

+0

我得到相同的錯誤 – AndrewVos

0

我可以試試子查詢來獲取最後一片葉子在每個樹。所以:

Tree.joins("INNER JOIN leafs l ON l.id = (SELECT id FROM leafs WHERE tree_id = trees.id ORDER BY created_at DESC LIMIT 1)") 
.where("leafs.state = ?", "connected") 

我希望這對你有所幫助。

+0

這選擇了連接葉子不是'latest_leaf'的樹。 – AndrewVos

+0

什麼是真正的表名「葉子」或「葉子」? – akbarbin

+0

沒有表,它是'has_one'。 – AndrewVos