0
0
Ruby on Railsframework~10 mins

Polymorphic associations in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a polymorphic association in a Rails model.

Ruby on Rails
class Comment < ApplicationRecord
  belongs_to :[1], polymorphic: true
end
Drag options to blanks, or click blank then click option'
Acommentable
Bcomment
Cpostable
Dcommented
Attempts:
3 left
💡 Hint
Common Mistakes
Using the model name 'comment' instead of the polymorphic association name.
Using a non-standard association name that doesn't match other models.
2fill in blank
medium

Complete the code to declare a polymorphic has_many association in a Rails model.

Ruby on Rails
class Post < ApplicationRecord
  has_many :[1], as: :commentable
end
Drag options to blanks, or click blank then click option'
Acommentables
Bcomments
Ccomment
Dposts
Attempts:
3 left
💡 Hint
Common Mistakes
Using singular form instead of plural for has_many.
Using a name that does not match the polymorphic association.
3fill in blank
hard

Fix the error in the migration to create a polymorphic reference.

Ruby on Rails
create_table :comments do |t|
  t.references :[1], polymorphic: true, null: false
  t.text :content
  t.timestamps
end
Drag options to blanks, or click blank then click option'
Acommentable
Bcomment
Ccommented
Dcomments
Attempts:
3 left
💡 Hint
Common Mistakes
Using the model name 'comment' instead of the polymorphic association name.
Using plural form in the reference name.
4fill in blank
hard

Fill both blanks to complete the polymorphic association in the model and migration.

Ruby on Rails
class Picture < ApplicationRecord
  belongs_to :[1], polymorphic: true
end

create_table :pictures do |t|
  t.references :[2], polymorphic: true, null: false
  t.string :image_url
  t.timestamps
end
Drag options to blanks, or click blank then click option'
Aimageable
Bpictureable
Cimage
Dpicture
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names in model and migration.
Using singular or plural inconsistently.
5fill in blank
hard

Fill all three blanks to create a polymorphic association with validations.

Ruby on Rails
class Tag < ApplicationRecord
  belongs_to :[1], polymorphic: true

  validates :[2], presence: true
  validates :[3], presence: true
end
Drag options to blanks, or click blank then click option'
Ataggable
Btaggable_id
Ctaggable_type
Dtag
Attempts:
3 left
💡 Hint
Common Mistakes
Validating the association name instead of the foreign key and type columns.
Using incorrect column names for validations.