penger
penger

Reputation: 3921

Pass object to has_many :conditions

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

Upvotes: 0

Views: 571

Answers (2)

EmFi
EmFi

Reputation: 23450

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

Upvotes: 2

Toms Mikoss
Toms Mikoss

Reputation: 9427

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?

Upvotes: 2

Related Questions