【问题标题】:How do I write a scope for some object from a many to many relationship?如何为多对多关系中的某个对象编写范围?
【发布时间】:2012-01-28 04:01:24
【问题描述】:

我需要编写一个范围,我将通过该范围传递用户的 ID,并从 users 表中收集与该用户的所有公司相关联的所有用户列表。

在 User.rb 中:

has_many :employments
has_many :companies, :through => :employments, :dependent => :destroy
...

在就业.rb:

belongs_to :user
belongs_to :company

在 Company.rb 中:

has_many :employments
has_many :users, :through => :employments, :dependent => :destroy

这可以通过以下方式实现:

current_user.companies.each{|c| c.users.each {|u| u}}

但我认为这样写更费时间。

【问题讨论】:

  • 如果执行 User.last!.companies 会发生什么?

标签: ruby-on-rails scope many-to-many


【解决方案1】:

以下(未测试)范围查找给定用户工作过的所有公司。

class Company
  has_many :employments
  has_many :users, :through => :employments, :dependent => :destroy

  scope :with_user, lambda { |user_id| joins(:employments).where(:user => user_id) }
  ...

运行 rails c 并执行 try Company.with_user(User.last!.id) 看看会发生什么。

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2013-04-08
    • 2012-12-03
    • 1970-01-01
    • 2014-11-08
    • 2018-10-16
    相关资源
    最近更新 更多