ActiveRecord find/include question (MySQL)


#1

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


#2

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