轨道 - 数据库逻辑,按公司划分的范围数据



我有3个模型:UserReceiptArticle

唯一的关联是:收据has_many物品。

现在我需要 4. 模型,这是Company.用户belongs_to公司,公司has_many用户。

用户只需要查看其公司中的收据和文章。 我是否需要在用户、收据和文章中company_id并按该 ID 浏览,或者有更好的方法?

用户只需要查看其公司中的收据和文章

像这样调整您的关联

#app/models/user.rb
class User < ApplicationRecord
belongs_to :company
end
#app/models/company.rb
class Company < ApplicationRecord
has_many :users
has_many :receipts
has_many :articles, through: :receipts
end
#app/models/receipt.rb
class Receipt < ApplicationRecord
belongs_to :company
has_many :articles
end
#app/models/article.rb
class Article < ApplicationRecord
belongs_to :receipt
end

现在您可以拨打@user.company.receipts@user.company.articles

我是否需要在用户、收据和文章中包含company_id并浏览 通过该 ID

使用上述方法,您需要company_idusersreceipts

除非您要使用多租户,否则您肯定需要在用户中拥有company_id。您还需要在收据中company_id,但不需要在文章中有,因为它已经与收据相关联。 要访问收据,您只需执行user.company.receipts

在两个表之间创建关系

class Receipt < ApplicationRecord
belongs_to :company
end
class Company < ApplicationRecord
has_many :receipts
end

使用该模型中的关系以简单的方式获取记录

例如:用户.公司.收据.第一条文章

最新更新