ruby on rails 4 - How to fetch an associated-through collection (proxied collection) using active-record methods -



ruby on rails 4 - How to fetch an associated-through collection (proxied collection) using active-record methods -

i have has_many relation between subscription , article, article has product.

class subscription < activerecord::base has_many :articles end class article < activerecord::base belongs_to :subscription belongs_to :product end class product < activerecord::base has_many :subscriptions end

now. i'd fetch products within subscriptions.

solution includes:

class subscription < activerecord::base has_many :articles def products articles.includes(:product).map{|a| ap.product} # or .map(&:product) end end

solution has_many :through:

class subscription < activerecord::base has_many :articles has_many :products, through: articles end

the first has downside not homecoming collection can chained upon (e.g. subscription.products.pluck(:id)), rather simple array.

the sec not exclusively 'semantically' correct: don't want become full-blown association, helper fetch list.

am overlooking activerecord method allows me fetch associated-through items?

i typically write "has_many through" returned products behave relation. accomplish similar in subscription method, add together missing has_many association product , merge subscription articles on product join:

class product < activerecord::base has_many :articles end class subscription < activerecord::base has_many :articles def products product.joins(:articles).merge(articles) end end

in case, subscription#products homecoming activerecord collection.

ruby-on-rails-4 rails-activerecord

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -