Forum: Ruby on Rails ActiveRecord find/include question (MySQL)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
gm g. (Guest)
on 2009-04-10 01:39
I found that if I do something like (on MySQL):

File.all(:conditions => {'files.deleted' => false, 'assets.deleted' =>
false}, :include => :assets)

will only return Files which have at least 1 assets associated with it.
If i removed the assets.deleted = 0  condition, then it returns all
Files, and their assets (if any); which is how I expected things to
behave.

now I can do something like:

File.all(:conditions => 'files.deleted AND (assets.file_id IS NULL OR
assets.deleted = 0)', :include => :assets)

And it will return all Files, and their assets (if any)...but righting a
query like this every time I do an include (i.e. almost all my tables
has a deleted bit) seems a bit cumbersome, as I prefer the hash
conditions over the string version.

Is there any way around this? Thanks
Frederick C. (Guest)
on 2009-04-10 02:07
(Received via mailing list)
On Apr 9, 10:39 pm, gm gm <removed_email_address@domain.invalid> wrote:
> now I can do something like:
>
> File.all(:conditions => 'files.deleted AND (assets.file_id IS NULL OR
> assets.deleted = 0)', :include => :assets)
>
> And it will return all Files, and their assets (if any)...but righting a
> query like this every time I do an include (i.e. almost all my tables
> has a deleted bit) seems a bit cumbersome, as I prefer the hash
> conditions over the string version.
>
> Is there any way around this? Thanks

Not really. When an include is done in a single query conditions apply
to all rows, which makes unobvious things like your first example
happen. You might be able to craft a named scope to alleviate the
typing work.

Fred
This topic is locked and can not be replied to.