ruby-on-rails - 如何使用范围连接多个表

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

我是 ROR 的新手,我正在尝试了解范围。在我当前的实现中,我正在获取所有处理器并将其显示在 View 中。

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 动中做到这一点
pry(main)> Processor.find(63).feed.groups.first.user.admin?

PS:如果关系很复杂,有人可以提供一些好的资源,让我可以学习如何使用范围。

最佳答案

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

至于资源,你有没有通过official documentation on ActiveRecord joins ?

关于ruby-on-rails - 如何使用范围连接多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19553758/

相关文章:

ruby-on-rails - rails : Warden/Devise - How to capture the url before login/failed access

javascript - Rails j 局部渲染

ruby-on-rails - 如何在 collection_select 标签中调用辅助方法

ruby-on-rails - 如何在Rails应用程序中汇总不同的货币?

ruby-on-rails - 如何生成带有数字的随机单词?

ruby-on-rails - Rails 3 file_store 缓存,删除过期片段

ruby-on-rails-3 - 理解 Rails/PG 解释

ruby-on-rails - 如何在 Rails 4 中使用 Tire gem 和 WillPaginate 对结果进行分页

sql - rails : ActiveRecord db sort operation case insensitive

mysql - 如何在 Ruby on Rails 中使用相同的 HTML 表单更新或保存记录?