2010-09-09 75 views
0

我有以下情況: 頁面有很多組。activerecord rails找到沒有組的頁面

現在我正在試圖找到沒有activerecord組的第一頁。 我試過這樣的事情:

Page.find(:first, :joins => :groups, :select => 'DISTINCT `pages`.*') 

但當然,至今沒有運氣。

回答

2

這更多的是一種SQL問題比ActiveRecord。你需要的是加入2個表格,但選擇那些在連接表格中沒有被引用的人員。

Page.first(:include => :groups, :conditions => ["`#{Group.table_name}`.id IS NULL"] 
# The opposite query would be 
Page.first(:include => :groups, :conditions => ["`#{Group.table_name}`.id IS NOT NULL"] 
# Note that this slightly different than just: 
Page.first(:include => :groups) 
# This produces a IN query, rather than join. 

而且:joins不起作用,因爲它創建了一個INNER JOIN,這不同於在這種情況下需要OUTER JOIN

+0

YEs這是更好!(我解決了循環所有網頁的問題..不是真的有效;)).. thanxs!:D – heldopslippers 2010-09-09 09:22:50

2

一個解決方案可能是爲組添加counter_cache。

在Group.rb

belongs_to :page, :counter_cache => true 

然後,你需要創建一個遷移

def self.up 
    add_column :pages, :groups_count, :integer, :default => 0 

    Page.reset_column_information 
    Page.find(:all).each do |p| 
    Page.update_counters p.id, :groups_count => p.groups.length 
    end 
end 

def self.down 
    remove_column :pages, :groups_count 
end 

所以,現在你可以這樣做:

Page.first(:conditions => { :groups_count => 0 }) 
+0

正常是這會工作。但我不太喜歡它,我應該爲這個簡單的聲明創建另一個遷移。 :(然後我可以做到這一點與SQL ..但thanxs! – heldopslippers 2010-09-09 08:22:27

0

喜歡的東西:

Page.find(:all, 
      :select => "pages.*, count(groups.page_id) group_count", 
      :joins => :groups, 
      :group => "pages.id having group_count = 0) 
相關問題