Rails 4通过对象列表获得嵌套关系

时间:2015-09-02 09:56:39

标签: ruby-on-rails

需要一些帮助。我正在尝试在处理对象列表时获取所有相关对象。 E g

class Customer
  has_many :items
end

class Item
  has_many :costs
  belongs_to :customer
end

class Cost
  belongs_to :item
end

我希望能够做到这样的事情:

Customer.where(name: 'Test').items.costs

问题似乎是你无法访问一组客户的has_many关系'items'。

关于如何实现这一目标的任何想法?

解决方案: 我选择了Nathan在下面评论中提出的解决方案:

Cost.where(item_id: Item.where(type: "hardware").pluck(:id))

这似乎是使用ActiveRecord获取集合的最简洁方法,尽管它需要两个SQL查询。

编辑: 由于dimakura在对他的建议的评论中提到这可能不可行,因为必须构建一个大型数组才能运行SQL。

编辑: 我只是想告诉你我的最终解决方案是什么。我想这样做的原因是获取用于我的应用程序中的统计信息的数据。例如“客户今年每个月购买物品多少钱?”。

最终我决定在每种情况下使用ActiveRecord创建统计信息是不可行的,这导致我使用纯SQL。可能有一些überclever方式以我想要的方式解决这个案例,但这个案例非常简单。还有其他一些难以解决的问题。

2 个答案:

答案 0 :(得分:2)

首先,在模型中定义以下关系:

class Customer < ActiveRecord::Base
  has_many :items
  has_many :costs, through: :items
end

class Item < ActiveRecord::Base
  belongs_to :customer
  has_many :costs
end

class Cost < ActiveRecord::Base
  belongs_to :item
end

现在您可以轻松选择此关系。

如果您需要从给定的costs中选择customer,那就是:

customer.costs

在更复杂的情况下,您可能需要为一组客户选择所有成本。在这种情况下,您使用joins编写查询。

让我们为美国客户选择成本:

Cost.joins(item: :customer).where('customers.country=?','US')

您现在不仅可以通过客户属性进行查询,还可以按项目属性进行查询。

希望它能解决你的问题。

答案 1 :(得分:0)

也许我错了,但根据我的说法,你需要做一些像

这样的事情
class Customer
  has_many :items
end

class Item
  belongs_to :customers
  has_many :costs
end

class Cost
  belongs_to :items
  attr_accessor :value
end