Search code examples
ruby-on-rails-3activerecordrelationships

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 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!


Solution

  • 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