Rails:Belongs_to Polymorphic Association +条件

时间:2014-10-24 08:38:29

标签: ruby-on-rails-3 activerecord relationships

所以我有这个模型:

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

  belongs_to :to, polymorphic: true

end

我想知道如果belongs_to属于特定类型,我是否可以添加另一种关系:

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,如果未设置,则返回{{1}}。

使用Rails 3.2

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用

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

表格更多了解association callbacks

答案 1 :(得分:0)

对于这种情况,假设我理解了你的问题,为了清楚起见,我可能会添加一个单独的方法。

def to_user
  #user-exclusive association retrieval
  type =  self.to_type == 'User'
  User.find(self.to_id) if type
end