Polymorphic association in rails?

Hi All,

Please provide idea or best practice link for polymorphic association step by step example.

Please explain with an compelete example.


Learning rails 6 .

the docs on this are actually a great reference and provide some examples that are really helpful

1 Like

I would like to know how to execute query on polymorphic association model.

i have Human, Company, Address, model.

Run command for Address model as :

rails g model Address h_number:string city:string country:string disst:string addressable:references{polymorphic}
class Human < ApplicationRecord
  belongs_to :company
  has_one :address, as: :addressable
class Company < ApplicationRecord
  has_many :humen
  has_one :address, as: :addressable
class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true


irb(main):036:0> Address
=> Address(id: integer, h_number: string, city: string, country: string, disst: string, addressable_type: string, addressable_id: integer, created_at: datetime, updated_at: datetime)
irb(main):037:0> Human
=> Human(id: integer, first_name: string, last_name: string, sal: integer, age: integer, company_name: string, company_id: integer, created_at: datetime, updated_at: datetime)
irb(main):038:0> Company
=> Company(id: integer, name: string, year: integer, emp: integer, head: string, value: integer, created_at: datetime, updated_at: datetime)

insert data

Company.create(name: "jain inc", year: 1994, emp: 15000, head: "bharat", value: 900000)
Human.create(first_name: "learning", last_name: "rails", sal: 70000, age:28, company_name: "jain inc", company_id: 1)

When i am execute query h = Human.first.address it is not getting address of comapny and human.

gettting nil :

Human Load (0.8ms)  SELECT "humen".* FROM "humen" ORDER BY "humen"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Address Load (0.7ms)  SELECT "addresses".* FROM "addresses" WHERE "addresses"."addressable_id" = $1 AND "addresses"."addressable_type" = $2 LIMIT $3  [["addressable_id", 1], ["addressable_type", "Human"], ["LIMIT", 1]]
=> nil

Please any idea how to get Address of Company and Human. One more thing i am a bit confuse about addressable, polymorphic association is it class or module or concern?


learning rails 6 .

please any idea for this ?

Spelling error. Not sure if this is the whole problem

this is fine, because it accept plural

Have you created Address records corresponding to the Human or Company you are looking for ?

For your example, an Address with those attributes : ["addressable_id", 1], ["addressable_type", "Human"]

no, can you explain?

how should I do this?

  addressable_type: 'Human', 
  addressable_id: 1, 
  city: 'my city'

Then you can retrieve it with h = Human.first.address

this is fine.

thank you