Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Is it possible to select has_many association column id as array

I have following models and has_and_belongs_to_many relationship, when I select my products

products =  Product.where()...., 

is it possible to select the associated stores ids or other store column as array in my query? so I can do

products[0].store_ids

to check what stores it belongs to.

class Product < ActiveRecord::Base
   has_and_belongs_to_many :store
end

class Store < ActiveRecord::Base
   has_and_belongs_to_many :products
end
like image 837
user1883793 Avatar asked Nov 27 '25 23:11

user1883793


1 Answers

store_ids is a magic method that has_and_belongs_to_many defines on Product's instance methods.

collection_singular_ids

Returns an array of the associated objects' ids.

See this for more info.

You don't have to eager load your associations, but it's a very good idea. As long as you have:

products = Product.includes(:stores)

Then you can call products[0].store_ids to get a list of store ids.

If you want to query on that association, you can do

Product.includes(:stores).where(stores: {some_field: 'Some Value'})

EDIT

If you want to get all unique products with their store ids, you can use array_agg with a group by since you're using Postgres.

products = Product
           .joins(:stores)
           .select('products.id, products.name, products.whichever_fields..., array_agg(stores.id) AS store_id_array')
           .group('products.id, products.name, products.whichever_fields...')

Then you will have products[0].store_id_array. Don't use store_ids since that will call the method defined by the has_and_belongs_to_many.

like image 50
Sean Hill Avatar answered Nov 30 '25 15:11

Sean Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!