Ruby on Rails - polymorphic association in ruby on rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
Example:
class Human < ActiveRecord::Base
has_one :address, :as => :addressable
end
class Company < ActiveRecord::Base
has_one :address, :as => :addressable
end
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
Without this association, we have all these foreign keys in our Address table but we only would ever have a value for one of them because an address, in this scenario, can only belong to one entity (Human or Company).
Output
It would look like:
class Address < ActiveRecord::Base
belongs_to :human
belongs_to :company
end