2010-12-09 51 views
0

我有一個功能,如:包括與條件,但始終顯示主表結果

# get all locations, if the user has discovered them or not 
def self.getAll(user) 
    self.find(:all, :order => 'min_level asc', :include => 'discovered_locations', 
    :conditions => [ "discovered_locations.user_id = ? OR discovered_locations.id is null", user.id]) 
end 

自我實際上是BossLocation模型。我想獲取bosslocation的結果集和發現的位置,如果該位置是我的用戶發現的。但是,如果它沒有被發現,我仍然需要bosslocation並且沒有對象作爲發現的位置。通過上面的代碼,如果用戶沒有發現任何東西,我根本就沒有得到bosslocations。

編輯:

我的關聯是這樣的:

class BossLocation < ActiveRecord::Base 

    has_many :discovered_locations 
    has_many :users, :through => :discovered_locations 

class DiscoveredLocation < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :boss_location 

class User < ActiveRecord::Base 
    has_many :discovered_locations 
    has_many :boss_locations, :through => :discovered_locations 

回答

0

我認爲問題在於你指定user_id的where條件而不是連接條件。如果用戶發現了BossLocation,或者根本沒有用戶發現它,則您的查詢將只會爲您提供BossLocation。

爲了使數據庫查詢符合您的需要,你可以改變包括以下連接:

:joins => "discovered_locations ON discovered_locations.boss_location_id = boss_locations.id 
      AND discovered_locations.user_id = '#{user.id}'" 

,但我不認爲這將幫助那麼多的Rails以來的渴望裝載不會在使用像這樣的連接而不是包含時工作。

如果我在哪裏做類似的事情,我可能會分裂它。也許通過增加協會用戶是這樣的:

class User < ActiveRecord::Base 
    has_many :disovered_locations 
    has_many :discovered_boss_locations, :through => :discovered_locations 

更新:

這樣的話,在你的控制器,你可以得到所有BossLocations和所有發現的BossLocations這樣的:

@locations = BossLocation.all 
@discovered = current_user.discovered_locations.all.group_by(&:boss_location_id) 

要使用這些當你通過他們循環,做這樣的事情:

<% @locations.each do |location| %> 
    <h1><%= location.name %></h1> 
    <% unless @discovered[location.id].nil? %> 
    <p>Discovered at <%= @discovered[location.id].first.created_at %></p> 
    <% end %> 
<% end %> 

Wh在此,它將所有發現的位置分組爲散列,其中密鑰是boss_location_id。所以當你循環遍歷所有boss_locations時,你只要看看發現的散列中是否有與boss_id匹配的條目。

-1

「的bosslocation的結果集和發現的位置,如果該位置被我的用戶發現,」這不是一個左外連接。你會隨時得到所有bosslocations。所以,你的條件是錯誤的!這將得到它的發現地點,它是discovered_locations.user_id = user.id或discovered_locations.id爲空「。在這種情況下,這可能很難爲一個s​​ql語句。你也可以在你的find_by_sql中使用union,但是我建議你使用兩個find函數。

+0

我很困惑,你會建議什麼命令? – Spyros 2010-12-09 09:49:42

+0

兩個發現手段'@locations = BossLocation.all @discovered = DiscoveredLocation.find(..)':P – rubyu2 2010-12-10 05:46:33