Created
August 29, 2013 03:03
-
-
Save sevenseacat/6373820 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Product < ActiveRecord::Base | |
| def self.supplied_within_states(*states) | |
| # So you can pass either an array or a list of arguments to the method | |
| states = states.flatten(1) | |
| if states.include? 'all' | |
| scoped | |
| else | |
| # Here be dragons! - RS 2013-05-20 | |
| # Ideally this query would be much simpler - something like: | |
| # scoped.joins(:product_variants => {:supplier_product_variants => :supplier}).merge(Supplier.in_states(states)) | |
| # to join all the tables and then filter on the final supplier table... however! | |
| # between Rails 3.0 not supporting nested has_many through associations (which is where the supplier table comes from) | |
| # and `merge` behaving a bit strangely with said nested HMT (support for this got added by a gem).. this is the final result | |
| # It takes a couple of queries (two here and several in the Supplier.in_states class method) but it does the job | |
| # When this app is upgraded to Rails 3.1+ this can be revisited (as it supports nested HMT natively | |
| # and probably has a bunch of other fixes too) | |
| scoped.where(:id => joins( :product_variants => { :supplier_product_variants => :supplier } ).where(:suppliers => {:id => Supplier.in_states(states).select(:id)})) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment