Rails: Belongs_to Polymorphic Association + conditions

坚强是说给别人听的谎言 提交于 2019-12-23 17:10:04

问题


So I have this model:

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

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

Using Rails 3.2

Thanks!


回答1:


You can use where condition inside that like

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

Form more have a look on this association callbacks




回答2:


for such a case, and assuming I understood your question, I would probably add a separate method for clarity.

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


来源:https://stackoverflow.com/questions/26544310/rails-belongs-to-polymorphic-association-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!