Association :conditions & instance-variable evaluation

Hello,

I was wondering if it’s possible to add :conditions to an association,
such that the conditions reference variables that need to be re-
evaluated before each query?

e.g.:
has_many :people, :conditions => “some_column =
@some_instance_variable, revision_time > #{Time.now},” etc.

When I tried an example binding a date column to Time.now, the time
didn’t change with each query. Instead, it continued using the
initial value of Time.now from when the class loaded.

Thanks,
Tom

On 20 Nov 2007, at 00:33, tom_302 wrote:

When I tried an example binding a date column to Time.now, the time
didn’t change with each query. Instead, it continued using the
initial value of Time.now from when the class loaded.

You can interpolate these things, but as you found

has_many :foos, :conditions => “#{xyz}”
doesn’t work: this statement is ran at class load and so the string is
interpolated

has_many :foos, :conditions => ‘#{xyz}’

should do the trick.

Fred

has_many :foos, :conditions => ‘#{xyz}’

Here’ my problem with the interpolation:

:conditions => ‘allow_spatial_resampling =
#{instance_var_that_evals_to_true}’

=> WHERE (allow_spatial_resampling = true)

Great, that works for MySQL, but not, say, SQLite. I need to do:

:conditions => [‘allow_spatial_resampling = ?’,
instance_var_that_evals_to_true]

=> MySQL: WHERE (allow_spatial_resampling = 1)

=> SQLite: WHERE (allow_spatial_resampling = ‘t’)

How can I have a DB agnostic solution, where obviously the latter won’t
work at the class level.

How can I have a DB agnostic solution, where obviously the latter won’t
work at the class level.

At least for my example, I found the solution:

:conditions => ‘allow_spatial_resampling =
#{quote_value(instance_var)}’

That works as expected, hope this helps someone out there.