Getting a nested object collection trough Active Record

夙愿已清 提交于 2019-12-25 03:56:31

问题


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

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

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?


回答1:


You could use

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


来源:https://stackoverflow.com/questions/7690463/getting-a-nested-object-collection-trough-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!