← Back to Upcase

Getting scoped results to include joined tables

(Jon Seidel) #1

For some reason, I cannot get my scoped results to include the attributes from a joins table. I’ve got a stores table which belongs_to a system_address table (has_one store) and I’ve tried:

scope :with_address, -> {
  joins(:system_address).select("store.*, system_address.*")


scope :with_address, -> {

and I still only get the stores table attributes.

Any suggestions as to what I’m missing?

(Derek Prior) #2

Your use case here doesn’t require the joins method. You only need that if you intend to use fields on the table you are joining to in your query.

includes(:system_address) should do what you want. The resuling Store models will not have columns from the SystemAddrress model available directly but accessing .system_address on an instance of Store will not incur another round trip to the database. The addresses returned in that query have been eager-loaded.

(Jon Seidel) #3

OK; thanks @derekprior; much appreciated! That works.