Topic: Symbols in :conditions always literal column names?

Hello,

I have a question about the :conditions hash in the various ActiveRecord query methods.

I have two tables...
Members: id, name, pcp_id
Providers: id, name

With the following models...

class Provider < AR::Base
end

class Member < AR:Base
  belongs_to  :pcp, :foreign_key => 'pcp_id', :class_name => 'Provider'
end


Now if I were to do this...
p1 = Provider.find(1)
p2 = Provider.find(2)
members = Member.find(:all, :conditions => {:pcp => [p1, p2]}) // error!

The result is an SQL exception because the generated query ends up looking like "select * from members where pcp in (1, 2)". 

I get what's happening:  AR interprets the :pcp symbol as a literal column name.  I was hoping that AR would be clever enough to use my belongs_to mapping to translate :pcp to the foreign key column name I gave it.  So I was hoping that the resulting SQL would be "... where pcp_id in (1, 2)". 

Is there some way I could have written the code above so that would have happened? Or is it just a fact of life that symbols in the :conditions hash are always interpreted as literal column names?

Re: Symbols in :conditions always literal column names?

Is there a reason you don't want to use pcp_id?

members = Member.find(:all, :conditions => {:pcp_id => [p1, p2]})

IIRC, using symbols in conditions like this was added in Rails 1.2. It is extremely simple and just does a very literal translation from the name of the symbol to the condition. It's not doing any kind of special interpreting or looking up associations AFAIK.

Railscasts - Free Ruby on Rails Screencasts

Re: Symbols in :conditions always literal column names?

ryanb wrote:

Is there a reason you don't want to use pcp_id?

IIRC, using symbols in conditions like this was added in Rails 1.2. It is extremely simple and just does a very literal translation from the name of the symbol to the condition. It's not doing any kind of special interpreting or looking up associations AFAIK.

No particular reason other than aesthetics I guess. I only ask because it seems like rails always  manages to do exactly what I think it should and it sticks out when I run into something where it doesn't.  I always sort of viewed conditions, even prior to 1.2 with symbols, as specifying property values on the model class.  It just so happened that the property names were the same as the column names since they were just dynamically built based on the table.  Not so with associations.  Although I would bet that there's a good chance that some future rails version will add this kind of functionality sooner or later.  Until then I can accept the way it is.

Last edited by ave (2007-02-03 10:36:06)