查询具有特定属性值的has_one模型

时间:2015-10-30 14:13:02

标签: ruby-on-rails ruby-on-rails-4 activerecord

我有两种模式:

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具有状态&#34;已连接&#34;。

2 个答案:

答案 0 :(得分:0)

如果您使用的是Rails 4,则可以使用:

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

答案 1 :(得分: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")

我希望这对你有所帮助。