【问题标题】:ActiveRecords Associations: Users, Reports, and GroupsActiveRecord 关联:用户、报告和组
【发布时间】:2016-01-25 00:21:57
【问题描述】:

ActiveRecords 关联的新手,还不能完全掌握它。我正在构建的应用程序应该使用户能够创建报告并加入/创建包含由成员生成的共享报告的组织。

这是我想出的,但是在阅读了这个主题之后,这似乎不太正确。

class User < ActiveRecord::Base
    has_many :reports, dependent: :destroy
    belongs_to :organizations
end

class Report < ActiveRecord::Base
    belongs_to :user
end

class Organization < ActiveRecord::Base
    #has_many :users
end

我将如何建立这些关联?任何建议将不胜感激!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord model associations


    【解决方案1】:
    class User < ActiveRecord::Base
      has_many :reports, dependent: :destroy
      belongs_to :organizations
    end
    
    class Report < ActiveRecord::Base
      belongs_to :user
    end
    
    class Organization < ActiveRecord::Base
      has_many :users
      has_many :reports, through: :users
    end
    

    这里的关键是has_many :reports, through: :users。当您执行 Organization.find(1).reports 时,这会告诉 Rails 通过加入用户关系来获取报告。

    【讨论】:

    • 感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多