我如何在 has_many 关联中指定动态条件
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能在
has_many
中使用动态条件。但是,在您的特定情况下,您似乎需要primary_key
和foreign_key
来代替:您可能也对 向 ActiveRecord 添加树结构的精华之一。
You cannot use dynamic conditions in
has_many
. However, in your particular case it seems you needprimary_key
andforeign_key
instead:You may also be interested by one of the gems that adds tree structure to ActiveRecord.