获得一个嵌套的对象收集槽活动记录 [英] Getting a nested object collection trough Active Record

查看:253
本文介绍了获得一个嵌套的对象收集槽活动记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检索对象槽活动记录名单,但没有成功。

I am trying to retrieve a list of object trough active record with no success

我有一个模型,它是:Store中有很多产品,产品有一个供应商

I have a model which is: Store has many Products, Product has one Supplier

class Store < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to  :supplier
  belongs_to  :store
end

class Supplier < ActiveRecord::Base
  has_many :products
end

我想获得供应商存储槽的产品像这样的列表:

I am trying to get a list of suppliers from store trough product like this:

self.products.supplier

这让我从ActiveRecord的::关系一个未定义的方法异常供应商

This gives me a undefined method exception 'supplier' from ActiveRecord::Relation

我应该做一个自定义查找这个还是有更好的办法?

Should I make a custom finder for this or is there a better way?

推荐答案

您可以使用

self.products.map{|product| product.suppliers}

或者你可以做到这一点,这在我看来是更好的

Or you could do this, which is better in my opinion

class Store
  has_many :suppliers, :through => :products
end

# Then you can use:
store.suppliers

这篇关于获得一个嵌套的对象收集槽活动记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆