ActiveRecords 关联:用户、报告和组
ActiveRecords Associations: Users, Reports, and Groups
ActiveRecords 关联的新手,还不能完全掌握它。我正在构建的应用程序应该允许用户创建报告,并且 join/create 包含成员生成的共享报告的组织。
这是我想出来的,但在阅读了这个主题之后,这似乎不太正确。
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
我将如何着手建立这些协会?任何建议将不胜感激!
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 通过加入用户关系来获取报告。
ActiveRecords 关联的新手,还不能完全掌握它。我正在构建的应用程序应该允许用户创建报告,并且 join/create 包含成员生成的共享报告的组织。
这是我想出来的,但在阅读了这个主题之后,这似乎不太正确。
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
我将如何着手建立这些协会?任何建议将不胜感激!
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 通过加入用户关系来获取报告。