如何在has_many关联中指定动态条件

时间:2011-07-12 04:47:14

标签: ruby-on-rails has-many conditional-statements

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>  

我甚至试过单引号:

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

时,它似乎没有考虑#{...}

我可以用范围来做     scope:threads,lambda {| conv_id | where(:conversation_id =&gt; conv_id)}
并访问它Message.where(“some condition”)。threads()
但我正在寻找像一个整洁的协会     m = Message.find(1000)     m.threads应该给出它所属的所有会话线程

1 个答案:

答案 0 :(得分: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感兴趣。