开发者

Getting a nested object collection trough Active Record

开发者 https://www.devze.com 2023-04-11 06:27 出处:网络
I am tryin开发者_如何学Gog 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

I am tryin开发者_如何学Gog 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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号