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
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'})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With