2009-09-14 80 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

相关问题