如何使用范围跨多个表进行连接

时间:2013-10-23 22:49:14

标签: ruby-on-rails ruby-on-rails-3

我是ROR的新手,我正在努力了解范围。在我当前的实现中,我将获取所有处理器并在视图中显示它。

class ProcessorsController
  def index
    @processors = Processor.all    
  end
end

我想修改它,以便我只能获得用户管理员的处理器。这就是我的关系建立的方式。

class Processor
  belongs_to :feed

  #SCOPES (what I have done so far)
  scope :feed, joins(:feed)
  scope :groups, joins(:feed => :groups).join(:user).where(:admin => true)
end

class Feed < ActiveRecord::Base
  has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :groups
  scope :admin,     where(:admin     => true)
end

我能够在我的撬中做到这一点

pry(main)> Processor.find(63).feed.groups.first.user.admin?
PS:有人可以提供一些好的资源,如果关系复杂,我可以学习如何使用范围。

2 个答案:

答案 0 :(得分:8)

scope :with_admin, -> { joins(:feed => { :groups => :user }).where('users.admin' => true) }

至于资源,您是否经历过official documentation on ActiveRecord joins

答案 1 :(得分:1)

您不需要范围...您只能使用关系和条件获得用户管理的处理器:

class Feed < ActiveRecord::Base
   ...
   has_one :user, through: :groups
end


class Processor
  ...
  has_one :admin, through: :feed, source: :user, conditions: ['users.admin = 1']
end