如何管理与 Rails 的 n:n 关系?

发布于 2024-08-06 08:17:29 字数 481 浏览 4 评论 0原文

假设我有一家公司,有许多员工,每个员工可以拥有许多公司

基本上我会有 :

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱&纷飞 2024-08-13 08:17:29

为了让所有以“John”开头的员工,您可以这样做(当然还有很多其他方法可以做到这一点,但无论如何):

some_company.employees.find(:all, :conditions => "name LIKE 'John%'")

对于员工的排序,它甚至更漂亮:

class Company < ActiveRecord::Base
  has_and_belongs_to_many :employees, :order => "name, email"
end

您可以使用 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):

some_company.employees.find(:all, :conditions => "name LIKE 'John%'")

For ordering of the employees it's even prettier:

class Company < ActiveRecord::Base
  has_and_belongs_to_many :employees, :order => "name, email"
end

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文