Rails Rails polymorphic 和 touch 混用,touch 功能失效

alanlong · 2015年06月24日 · 最后由 alanlong 回复于 2015年06月24日 · 2211 次阅读

在 model 层 polymorphic 可以实现多态关联的功能,如网上这个比较简单的例子:

lass Person < ActiveRecord::Base  
  has_one :address, :as => :addressable  
end  

class Company < ActiveRecord::Base  
  has_one :address, :as => :addressable  
end  

class Address < ActiveRecord::Base  
 belongs_to :addressable, :polymorphic => true  
end  

这样 Address 有 adressable_id addressable_type 其中,addressable_type 可以为 Company 或者 Person。 而 touch 则能实现当子表的记录更新或增加时,父表的记录更新,如

class Person < ActiveRecord::Base  
  has_one :address, :as => :addressable  
end  

class Address < ActiveRecord::Base  
 belongs_to :addressable, :touch=> true  
end  

这样,当 person.addresses.first update, person.updated_on 会更新。 但是当 polymorphic 和 touch 同时使用,即 如果将第一段代码中

class Address < ActiveRecord::Base  
 belongs_to :addressable, :polymorphic => true  
end  
## 改成
class Address < ActiveRecord::Base  
 belongs_to :addressable, :polymorphic => true, :touch => true
end  

的时候,父表记录中的 updated_on 是不会更新的。[PS: 应该是编译器不知道如何去找父表] 请问有什么方法可以在实现多态关联的前提下更新父表的记录吗? 谢谢!

问题已经解决了,http://stackoverflow.com/questions/4976989/can-touch-be-used-on-a-belongs-to-polymorphic-relationship-in-rails stackoverflow 上有人给了解释。这两个是能够同时使用的,只是需要在 Address 中将 addressable 加入到 attr_accessible 即可

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