新手问题 关于多态的问题

hexawing · 2014年01月13日 · 最后由 hexawing 回复于 2014年01月14日 · 2382 次阅读

现实情况是这样的: 员工要写工作日志,但根据岗位,一部分是 sale_log,一部分是 service_log,因为数据结构等已经做成了两个表。 然后这两个表都有可能会生成报价,所以就把报价表给做成多态了。

class Quote < ActiveRecord::Base
    belongs_to :quotable, :polymorphic => true
end
class ServiceLog < ActiveRecord::Base
    has_one :quote, :as => :quotable
end
class SaleLog < ActiveRecord::Base
    has_one :quote, :as => :quotable
end

然后就遇到了问题:

>>SaleLog.where("quotes.id = 5").includes(:quote).size#从这个方向查询可以
0
>> Quote.where("sale_logs.id = 5").includes(:quotable).size#反过来查就不行了……
ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :quotable
>> Quote.where("sale_logs.id = 5").includes(:sale_log).size#这个必然也不行……
ActiveRecord::ConfigurationError: Association named 'sale_log' was not found; perhaps you misspelled it?

这个要怎么写才对呢……

#1 楼 @LarryLv 谢谢。我看了一下,它说的应该是这样:

>>Quote.last.quotable
#<SaleLog id: 8355, process: 7, ...>

我那个要求我还是只能用.joins("left join xxxxx")实现了……

需要 登录 后方可回复, 如果你还没有账号请 注册新账号