On Tue, Jun 2, 2009 at 3:38 PM, Erik Dahlstrand
<[email protected]> wrote:
>
> Hi,
>
> I have a polymorphic association between Company and Address.
>
> class Address < ActiveRecord::Base
>  belongs_to :addressable, :polymorphic => true
> end
>
> class Company < ActiveRecord::Base
>  has_many :addresses, :as => :addressable, :dependent => :destroy
> end
>
> I want to fetch all addresses that fulfills conditions on both Company
> and Address. The following query does not work but it illustrates what
> I want to achieve.
>
> Address.all :joins => :companies, :conditions => { :companies =>
> { :reseller => true }, :addresses => { :geocoded => true } }

As far as I know, you can't use a nested hash for :conditions

> The following SQL query does the job but I want to do it with a single
> Active Record Query. Is that possible?
>
> SELECT addresses.* FROM addresses
> INNER JOIN companies ON companies.id = addresses.addressable_id AND
> addresses.addressable_type = 'Company'
> WHERE (addresses.geocoded = 't'
>  AND addresses.address_type = 2
>  AND companies.reseller = 't'
>  AND companies.enabled = 't')

Well that's not the query I'd have expected from your nested hash
condition if it worked, but something like this

Address.find(:all, :joins => :companies, :conditions =>
['addresses.geocoded = ? AND addresses.address_type = ? andd
companies.reseller = ? AND companies.enables = ', true, 2, true,
true])

Might work.


-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to