简体   繁体   English

如何在Ruby on Rails应用中为公司和人员建模?

[英]How to model Companies and Persons in a Ruby on Rails app?

I am new to Rails and I am trying to build an application where one User can have many Organisations which can have many Persons which in turn can have many Projects . 我是Rails的新手,我正在尝试构建一个应用程序,其中一个用户可以拥有许多组织 ,这些组织可以拥有许多 ,而这些又可以拥有许多项目

These are my models (does it make sense at all?): 这些是我的模型(完全有意义吗?):

Users ---< Companies ---< Persons ---< Projects 用户--- <公司--- <人员--- <项目

Now my key question is what will happen if a person does not belong to any company at all? 现在我的关键问题是,如果一个人根本不属于任何公司,将会发生什么? Will my application still work and will I still be able to access projects, for example like this... 我的应用程序仍然可以运行,并且仍然可以访问项目吗?

current_user.persons.projects

...despite there being no company? ...尽管没有公司?

There is probably a fairly simple way to model these tables in Rails, but for some reason I just can't get my head around this. 在Rails中可能有一种相当简单的方法来对这些表进行建模,但是由于某种原因,我无法解决这个问题。 Thanks for any help. 谢谢你的帮助。

Person and Organization is not a hierarchical relationship. 人与组织不是等级关系。 It seems like one, but it isn't. 看起来像一个,但事实并非如此。 It's a graph. 这是一张图。

An organization can have 0+ sub-organizations. 一个组织可以有0个以上的子组织。 It can have 0+ employees over time, and a person can work for more than one organization at the same time. 随着时间的推移,它可以有0+名员工,并且一个人可以同时为多个组织工作。

You can also sell to, or purchase from an individual or an organization, so you must model them as the same super-type. 您还可以向个人或组织出售或购买,因此必须将它们建模为相同的超级类型。

This is called the Party model and I would suggest reading up on it here before you start. 这就是所谓的“聚会模式”,我建议您在开始之前在此进行阅读。

You want to look into using the 您想研究使用

belongs_to and has_many in your models. 您模型中的belongs_to和has_many。

Check out this guide below. 在下面查看此指南。

http://guides.rubyonrails.org/association_basics.html http://guides.rubyonrails.org/association_basics.html

With associations you can set up a structure, as posted in the answer by ge0man. 通过关联,您可以建立一个结构,如ge0man在答案中所述。

With validations you can make sure the model has the right properties required before saving / updating. 通过验证,您可以确保模型具有保存/更新之前所需的正确属性。

If you dont and you call a function like User.projects it will just return an empty array, because no project listed to that user were found :) 如果不这样做,则调用User.projects之类的函数,它将仅返回一个空数组,因为未找到该用户列出的项目:)

Now my key question is what will happen if a person does not belong to any company at all? 现在我的关键问题是,如果一个人根本不属于任何公司,将会发生什么? Will my application still work and will I still be able to access projects, for example like this... 我的应用程序仍然可以运行,并且仍然可以访问项目吗?

Answer to your key question is: yes, any user will be able to access projects that belong to people with no company thus: 您的关键问题的答案是:是的,任何用户都可以访问没有公司的人的项目,因此:

Project.all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM