【问题标题】:has_many inheritancehas_many 继承
【发布时间】:2010-03-25 09:15:50
【问题描述】:

我有一个名为 company 的模型,它拥有_many 用户然后用户属于_to 公司。

class Company < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :company
end

如果某物属于用户,它是否也属于公司?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      相关资源
      最近更新 更多