2009-09-14 54 views
2

攝影師「have_many」客戶。有沒有更好的方式來獲取這些數據?

客戶端「have_many」事件。

如果用戶是攝影師,是否有更好的方法在這裏分配@events?

def index 
    if @current_user.photographer? 
     @events = [] 
     @current_user.clients.each do |client| 
     @events << client.events 
     end 
    else 
     @events = @current_user.events 
    end 
    end 

編輯:更多的代碼

# user.rb 
class User < ActiveRecord::Base 

    has_many :client_associations, 
     :foreign_key => 'photographer_id', 
     :class_name => 'Association', 
     :dependent => :destroy 
    has_many :clients, :through => :client_associations 

    has_one :photographer_association, 
    :foreign_key => 'client_id', 
    :class_name => 'Association', 
    :dependent => :destroy 
    has_one :photographer, :through => :photographer_association 

    has_many :events 

    def photographer? 
    self.role == 'photographer' 
    end 

end 

# association.rb 
class Association < ActiveRecord::Base 
    belongs_to :client, :class_name => "User" 
    belongs_to :photographer, :class_name => "User" 
end 

# event.rb 
class Event < ActiveRecord::Base 
    belongs_to :user 
    has_many :images  
end 

正如你可以看到我的用戶都在一個叫做「角色」字段中的一個典範。

回答

2

從db的角度來看,您應該一次加載所有事件並且不會出現N + 1問題。

def index 
    if @current_user.photographer? 
     @events = @current_user.clients.find(:all, :include => :events).map(&:events).flatten 
    else 
     @events = @current_user.events 
    end 
    end 
+0

可能值得注意的是'.map(&:events)'因爲這個原因而工作:http://invisibleblocks.wordpress.com/2008/03/28/ruby-facets-symbolto_proc-classto_proc/ – 2009-09-14 19:21:24

0

這種邏輯,恕我直言,會更好地設置在模型層。

您可以創建一個新的模型的方法,比如在用戶模式current_events,並有移動你的邏輯:

def current_events 
    if self.photographer? 
     self.clients.find(:all, :include => :events).map(&:events).flatten 
    else 
     self.events 
    end 
end 

然後,控制器上,你可以只添加

def index 
    @events = @current_user.current_events 
end 

因此,你的邏輯被封裝在你的模型上(並且以後我可以改進,添加更復雜的測試),你的控制器不需要知道(和關心)它是什麼,只需調用並顯示用戶的current_events即可。

+0

從他的代碼:「@events = @ current_user.events」看起來像用戶模型已經有事件,並沒有通過客戶端。 – amitkaz 2009-09-14 15:37:49

+0

我不太確定,事先沒有一些代碼。看起來他所稱的「事件」方法是針對客戶端模型。不知道它是從用戶下降。 – Yaraher 2009-09-14 15:53:04

+0

lemme添加一些代碼... – 2009-09-14 16:36:47

相關問題