ruby-on-rails - ActiveRecord 联接获取子对象而不是父对象

标签 ruby-on-rails ruby join activerecord ruby-on-rails-4

我的问题:

我有三个模型:公司、 parent 和 child 。

child belongs_to parent belongs_to 公司

我需要获取一家公司内某个属性设置为 false 的所有 child 。 (Parent 模型有 company_id 而 Child 模型没有。)

我正在尝试:

我有以下连接:

@objects = Parent.joins(:childs).where('parents.company_id' => current_user.company_id, 'childs.foo' => false)

在我看来:

<!-- This should be a list of child objects -->
<% @objects.each do |obj| %>
<%= obj.foo %>
<% end %>

(foo是子对象的属性)

模型:

class Company < ActiveRecord::Base
  has_many :parents, :dependent => :destroy
  ...
end


class Parent < ActiveRecord::Base
  has_many :childs, :dependent => :destroy
  belongs_to :company
  ...
end


class Child < ActiveRecord::Base
  belongs_to :parent
  ...
end

但是,编写 Parent.joins(:childs)... 会返回 Parent 对象的 ActiveRecord 关系。 (当我尝试访问子属性时抛出错误)我需要结束列表是子对象。但我发现这样做很难。

这个问题的一个很好的答案是:

  • 以另一种方式解决了这个问题,这种方式更有意义,而且计算量不会太大。

  • 或显示如何获取子对象而不是父对象的列表/关系的内容。

最佳答案

简单,从子类开始:

Child.joins(:parent).where(parents: {company_id: current_user.company_id}, foo: false)

我可能会建议使用范围/类方法以更简洁的方式完成此任务:

class Parent < ActiveRecord::Base
  def self.for_user(user)
    where(company_id: user.company_id)
  end
end

class Child < ActiveRecord::Base
  scope :fooless, ->{where foo: false}
end

现在你可以这样做了:

Child.joins(:parent).merge(Parent.for_user(current_user)).fooless

关于ruby-on-rails - ActiveRecord 联接获取子对象而不是父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26806905/

相关文章:

ruby-on-rails - Rails 4 - 如何在/config/environments/production.rb 文件中使用常量?

ruby-on-rails - 如何在 Slim 模板中渲染 HTML

ruby - 动态需要文件?

ruby - 如何扩展 Ruby Enumerable 类 max_by 以忽略 nil?

mysql - 使用 count inside count 时将结果限制为 1 的 SQL 查询

mysql - 改进我的查询

ruby-on-rails - 使用 RESTful session 在 Controller 之间传递数据

ruby-on-rails - Rails_admin 不显示所有包含的模型

ruby-on-rails - 通过 Heroku Rails 应用程序使用 DNS 和 SMTP 检查进行电子邮件验证

mysql - 只列出在 mysql 中出现三次的行