say have following models:
class category < activerecord::base has_and_belongs_to_many :items end class item < activerecord::base has_and_belongs_to_many :categories end
i'm building endpoint retrieves items, each item should coupled array of category ids belongs to. example result be:
[ { name: 'my item', category_ids: [1, 2, 3] }, // more items... ]
with configuration, i'm able call item.category_ids
on each record results in sql want, looks select categories.id categories inner join categories_items ... categories_items.item_id = $1
.
however, results in n+1 - , can't seem find way in eager load. i'm looking list of items, , just id of categories they're in, eager loading category_ids
field of each item
(although, if there's way accomplish same using eager loading i'm okay well)
edit explain difference duplicate:
i'm looking see if it's possible 2 in 2 separate queries. 1 fetches items, , 1 fetches category ids. items table relatively wide, i'd prefer not multiply number of rows returned number of categories each item has - if possible.
using join model instead of has_and_belongs_to_many
allow query join table directly instead (without hacking out query yourself):
class category < activerecord::base has_many :item_categories has_many :items, through: :item_categories end class item < activerecord::base has_many :item_categories has_many :categories, through: :item_categories end class itemcategory belongs_to :item belongs_to :category end
note table naming scheme has_many through:
different - instead of items_categories
item_categories
. constant lookup work correctly (otherwise rails looks items::category
join model!) - need migration rename table.
items = item.all category_ids = itemcategory.where(item_id: items.ids).pluck(:category_id)
Comments
Post a Comment