如何管理与 Rails 的 n:n 关系?
假设我有一家公司
,有许多员工
,每个员工
可以拥有许多公司
。
基本上我会有 :
class Employee < ActiveRecord::Base
has_and_belongs_to_many :companies
end
然后
class Company < ActiveRecord::Base
has_and_belongs_to_many :employees
end
我很困惑如何得到这样的东西:
- 名称以“John”开头的公司的所有员工
- 公司的所有员工首先按姓名排序,其次是电子邮件。
难道还有什么我不知道的魔法吗?该示例仅用于演示,如果可以帮助您更好地解释,请随意做出假设或更改它。
Let's say I have a Company
that has many Employees
and each Employee
can have many Companies
.
Basically I will have :
class Employee < ActiveRecord::Base
has_and_belongs_to_many :companies
end
and
class Company < ActiveRecord::Base
has_and_belongs_to_many :employees
end
But then I'm confused about how I could get things like:
- All the employees of a company with the name starting by "John"
- All the employees of a company order by name first, email second.
Is there some magic I don't know about? The example is just here for the demo, feel free to make assumptions or change it if it helps you explain better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了让所有以“John”开头的员工,您可以这样做(当然还有很多其他方法可以做到这一点,但无论如何):
对于员工的排序,它甚至更漂亮:
您可以使用 ActiveRecord 做更多的事情。我建议您尝试阅读 http://guides.rubyonrails.org/ 或观看 http://railscasts.com/ 了解更多有关 RoR 之美的信息 =)
希望它有所帮助!
For getting all the employees starting with "John", you can do (of course there are many other ways to do it, but anyway):
For ordering of the employees it's even prettier:
There are a whole lot more you can do with ActiveRecord. I suggest that you try reading up on http://guides.rubyonrails.org/ or watch http://railscasts.com/ to learn more about the beauty of RoR =)
Hope it helps!