Rails: Belongs_to Polymorphic Association + Conditions

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 a property is of a certain 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 to_type...
end

      

To my_model.to_user

return user

if it exists and nil

if it is not set or has a different class.

Using Rails 3.2

Thank!

+3


source to share


2 answers


You can use the terms in which it is used

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

      



See this association callback for more details

+2


source


for such a case, and assuming I understood your question, I will 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

      

0


source







All Articles