Rails:属于多态关联+条件 [英] Rails: Belongs_to Polymorphic Association + conditions

查看:95
本文介绍了Rails:属于多态关联+条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个模型:

class Model < ActiveRecord::Base
  attr_accessible :to_id, :to_type

  belongs_to :to, polymorphic: true

end

我想知道当归属类型为特定类型时是否可以添加其他关系:

I was wondering if I could add another relationship when belongs_to is on a specific type:

class Model < ActiveRecord::Base
  attr_accessible :to_id, :to_type

  belongs_to :to, polymorphic: true
  belongs_to :to_user, :foreign_key => :to_id, :conditions => ['to_type = ?', 'User'] # doesn't work
  # OR MAYBE
  belongs_to :to_user, :foreign_key => :to_id, :foreign_class => 'User' # It doesn't check on Model's to_type...
end

my_model.to_user 将返回 user (如果存在),以及 nil 如果未设置或属于其他类别。

So that my_model.to_user would return the user if exists, and nil if unset or of different class.

使用Rails 3.2

Using Rails 3.2

谢谢!

推荐答案

您可以使用

 belongs_to :to_user,-> {where(:to_type=> 'User')},  :foreign_key => :to_id

更多信息请参见关联回调

这篇关于Rails:属于多态关联+条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆