2011-07-12 88 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

我試過has_many:threads,:class_name =>「Message」,:conditions =>'conversation_id = 1',我得到未知列'message_id' –

回答

2

您不能使用has_many中的動態條件。然而,在您的特定情況下,它似乎你需要primary_keyforeign_key代替:

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

您也可以通過one of the gems that adds tree structure to ActiveRecord感興趣。

+0

謝謝。那工作。實際上我認爲它只支持foreign_key。它是有據可查的。我的錯 :) –