我有3个与habtm协会相关的课程......用户,地点,员工。
用户通过habtm关系与Locations相关,Locations通过habtm关系与Employees相关。
我希望能够做到的是:
current_user.locations.employees
有没有人知道“Rails Way”这样做?我可以在SQL中完成它,但我想知道是否有更简洁的方法。
答案 0 :(得分:1)
您可以在ActiveRecord中扩展关联:
class User
has_many :locations do
def employees
# Use whatever logic you'd like here.
locations.find(:all, :include => [:employees]).collect {|l| l.employees }
end
end
end
u = User.find 1
u.locations.employees #=> calls our method defined above
看到这个:
http://ryandaigle.com/articles/2006/12/3/extend-your-activerecord-association-methods
您也可以尝试has_many :through
:
class User
has_many :user_locations
has_many :locations, :through => :user_locations
# Not sure if you can nest this far, this guy has problems with it:
# http://tim.theenchanter.com/2008/10/how-to-hasmany-through-hasmany-through.html
#
# Maybe if locations was a habtm instead of :through? experiment with it!
#
has_many :employees, :through => :locations
end
u = User.find 1
u.employees #=> Uses associations to figure out the SQL
总的来说,李,我关心你的数据模型。现在不建议使用HABTM关系。使用has_many :through
允许您命名连接表,然后您可以在具有更好业务含义的关系上存储属性。我会说“Railsy”的事情是通过关系添加一些来揭示更多的域建模。
此外,一些示例模型有助于真正理解您的问题。
祝你好运!答案 1 :(得分:0)
我认为以下情况属实,您的ActiveRecords将反映这一点。
user belongs_to location
location has_many users
location has_many employees
employee belongs_to location
然后你可以在你的用户ActiveRecord中说出
has_many :employees :through => :locations
我认为这应该有用。
更新:
刚刚意识到您的用户也有很多位置。不太确定上述是否有效。值得一试。
答案 2 :(得分:0)
您可以在用户排序中定义方法,如下所示
def get_all_related_employees
employees = []
self.locations.each do |location|
employees << location.employees
end
employees
end
或者你可以直接内联
current_user.locations.map {|location| location.employees }.each do |employee|
puts employee.name
end