0
我有一個叫做公司的模型,has_many用戶,然後用戶belongs_to公司。has_many繼承
class Company < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :company
end
如果是屬於用戶的東西,它也屬於公司嗎?
我有一個叫做公司的模型,has_many用戶,然後用戶belongs_to公司。has_many繼承
class Company < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :company
end
如果是屬於用戶的東西,它也屬於公司嗎?
您必須爲此使用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
確定這是有道理的感謝。 – shaneburgess 2010-03-25 01:27:36