Rails: Belongs_to Polymorphic Association + condit

2019-07-07 09: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