Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord (Rails): How to do custom (SQL) joins in Rails without an association?

I can write this query which touches 2 tables and gives me the results I want:

select inv.* from
item_to_sku its
left join inventory inv on its.sku_id=inv.sku_id
where its.item_id in (12345, 67890)

And I can come close to it in Rails with this:

ItemToSku.includes(:sku => :inventory).find_all_by_item_id([12345, 67890])

But that pointlessly involves the SKU table in this. Since both ItemToSku and Inventory have a sku_id, I want to just join them directly together like in the SQL version above.

Without adding confusing associations onto my many-to-many table model (ItemToSku), how can I write an appropriate ActiveRecordy way of doing this? I've been playing with .joins() but I can't find any examples of using .joins without existing associations. The main reason I don't want to create the associations is that there are like 20 associations on Sku and more on Item, and it seems silly to duplicate them and thus cloud up the true associations just to optimize one query.

like image 337
XP84 Avatar asked Dec 12 '13 17:12

XP84


1 Answers

joins can be used in multiple ways.

i. Join association

  1. Single

  2. Multiple

  3. Nested

ii. Join using raw sql(what you are looking for)

 ItemToSku.joins("LEFT JOIN inventory ON item_to_sku.sku_id = inventory.sku_id").where("item_id in (?)", [12345, 67890])

Note: includes is used for eager loading

like image 164
usha Avatar answered Oct 31 '22 00:10

usha