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

发布于 2024-11-19 08:08:08 字数 883 浏览 0 评论 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>  

我什至尝试过使用单引号:

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 时没有考虑 #{...} 的事情,

我可以使用范围来做到这一点
范围:线程,lambda {|conv_id|其中(:conversation_id => conv_id) }
并访问它 Message.where("some condition").threads()
但我正在寻找一个简洁的关联,例如
m = 消息.find(1000) m.threads 应该给出它所属的所有对话线程

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>  

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白况 2024-11-26 08:08:08

您不能在 has_many 中使用动态条件。但是,在您的特定情况下,您似乎需要 primary_keyforeign_key 来代替:

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

您可能也对 向 ActiveRecord 添加树结构的精华之一

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文