Rails has_many and dynamic conditions

13 Jul
2009

Just had the problem, that I wanted a has_many association in my model with a condition from a value of the same model. Turns out this is quite hard.

I know there are named_scopes, but a has_many is needed if you want to use rails’ great query methods.

You see, this condition is parsed at runtime (because we use single quotes) – and reads the current model version (lock_version) via a self.send.

has_many :tc_links, :conditions => '`#{TcLink.table_name}`.tc_version = #{self.send(:lock_version)}'

It’s working, but I don’t really like this syntax. Are there any better solutions for my problem?

Anyway, here’s the source: http://alexle.net/archives/235

Related posts:

  1. Demystifiying Rails Model attributes overriding
  2. Rails + Google App Engine !?

Comment Form

top

Switch to our mobile site