views:

52

answers:

2

Hi guys, I need to pass self as object not class to :conditions string, is there any way to do this?

has_many :topic,
:class => 'FileTopic',
:conditions => "id in (select * from file_topics where program_id = #{self.id})"

My problem is self is always giving me the id of the class but not the instance of the class. I guess has_many is evaluated on the class level?

Thanks

+1  A: 

It is evalued upon loading the class, yeah. But only if you use double quotes - variables in single-quoted strings are filled upon calling. More info here.

However, maybe you should look into named scopes?

Toms Mikoss
+1  A: 

Has many is a class method. So any reference to self in its arguments are references to the class.

It looks like you want to specify the foreign key on the belongs_to side of things.

Have you tried this yet:

has_many :topic, :class => 'FileTopic', :foreign_key => "program_id"

You should really have a read through the ActiveRecord::Associations documentation if you haven't yet. There are very few association problems that can't be solved using the right set of options to belongs_to/has_one/has_many

EmFi
the example i show here is way simpler than the actual thing. The association actually has UNION and some virtual tables in it.
penger
As far as rails goes, UNIONs can be accomplished with polymorphic associations. There's probably a Rails Way to do virtual tables, without seeing what you're trying to achieve I can't advise. It's possible a :through relationship on a complex association, might work.
EmFi