class Message
has_many :threads, :class_nam开发者_如何学JAVAe=>"Message", :conditions => "`#{Message.table_name}`.conversation_id = #{self.send(:conversation_id)}"
end
m = Message.first
NoMethodError: undefined method `conversation_id' for #<Class:0xc5021dc>
I even tried with single quote:
class Message
has_many :threads, :class_name=>"Message", :conditions => '`#{Message.table_name}`.conversation_id = #{self.send(:conversation_id)}'
end
m = Message.first
m.threads
This gave me Mysql::Error: You have an error in your SQL syntax
#{...}
thing while generating the condition sql
i could do it with scopes
scope :threads, lambda {|conv_id| where(:conversation_id => conv_id) } and access it Message.where("some condition").threads() but am looking for a neat association like m = Message.find(1000) m.threads should give all the conversation threads which it belongs toYou cannot use dynamic conditions in has_many
. However, in your particular case it seems you need primary_key
and foreign_key
instead:
class Message
has_many :threads, :class_name=>"Message", :primary_key => 'conversation_id', :foreign_key => 'conversation_id'
end
You may also be interested by one of the gems that adds tree structure to ActiveRecord.
精彩评论