开发者

how can i specify dynamic conditions in has_many associations

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

It seems it's not considering the #{...} 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 to


You 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜