2010-03-25 97 views
0

我有一个叫做公司的模型,has_many用户,然后用户belongs_to公司。has_many继承

class Company < ActiveRecord::Base 
    has_many :users 
end 

class User < ActiveRecord::Base 
    belongs_to :company 
end 

如果是属于用户的东西,它也属于公司吗?

回答

1

您必须为此使用has_many :through关联。

class Comment < ActiveRecord::Base 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    belongs_to :company 
    has_many :comments 
end 

class Company < ActiveRecord::Base 
    has_many :users 
    has_many :comments, :through => :users 
end 

现在,你可以做到以下几点:

c = Company.first 
c.users # returns users 
c.comments # returns all the comments made by all the users in the company 
+0

确定这是有道理的感谢。 – shaneburgess 2010-03-25 01:27:36