摄影师“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
正如你可以看到我的用户都在一个叫做“角色”字段中的一个典范。
可能值得注意的是'.map(&:events)'因为这个原因而工作:http://invisibleblocks.wordpress.com/2008/03/28/ruby-facets-symbolto_proc-classto_proc/ – 2009-09-14 19:21:24