2011-07-12 22 views
0
class Message 
    has_many :threads, :class_name=>"Message", :conditions => "`#{Message.table_name}`.conversation_id = #{self.send(:conversation_id)}" 
end 

m = Message.first 
NoMethodError: undefined method `conversation_id' for #<Class:0xc5021dc> 

にhas_many団体での動的な条件を指定する方法:私は、私も一重引用符で試してみました

class Message 
    has_many :threads, :class_name=>"Message", :conditions => '`#{Message.table_name}`.conversation_id = #{self.send(:conversation_id)}' 
end 

m = Message.first 
m.threads 

はこれが私に与えたのMysql::Error: You have an error in your SQL syntaxことが条件SQL

を発生させながら、それは #{...}事を考慮していないようだ

私はスコープでそれを行うことができました
スコープ:threads、lambda {| conv_id |ここで、(:conversation_id => conv_id)。}
とアクセスそれはMessage.where( "いくつかの条件")のスレッド()
が、
メートル= Message.find(1000) メートルのようなきちんとした団体を探しています。スレッドが属しているすべての会話スレッドを提供する必要があります

+0

私はhave_many:threads、:class_name => "Message"、:conditions => 'conversation_id = 1'を試してみましたが、未知の列 'message_id'を取得しました –

答えて

2

has_manyでは動的条件を使用できません。あなたはまた、one of the gems that adds tree structure to ActiveRecordによって興味がある可能性があり

class Message 
    has_many :threads, :class_name=>"Message", :primary_key => 'conversation_id', :foreign_key => 'conversation_id' 
end 

:しかし、あなたの特定のケースでは、あなたがprimary_key、代わりにforeign_keyを必要とするようです。

+0

ありがとうございます。それはうまくいった。実際に私はそれがforeign_keyだけをサポートしていると思った。それは十分に文書化されている。私の間違い:) –

関連する問題