views:

26

answers:

1

Rails: I need to set a condition in a has_many that needs the self.id variable

I need something like this: has_many :posts, :conditions => "posts.hello_id = #{self.id}" but self.id there it just doesnt work :s

A: 

This should work

class Bar
  has_many :foo, :conditions => "bar_id is NULL"
end

class Foo
  belongs_to :bar
end

Basically, you are providing SQL as the condition.

Another option, although I have never tried it myself, may be to use :finder_sql

has_many :posts, :finder_sql => 'select * from posts where hello_id = #{primary_key}'
Randy Simon
I need something like this:has_many :posts, :conditions => "posts.hello_id = #{self.id}"but self.id there it just doesnt work :s
Totty
Posting your object model would help here. Is this statement in the Hello class? If so, that condition is not needed assuming that the Posts class has a belongs_to :hello statement.
Randy Simon