0
0
Ruby on Railsframework~10 mins

belongs_to relationship 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 belongs_to association in a Rails model.

Ruby on Rails
class Comment < ApplicationRecord
  [1] :post
end
Drag options to blanks, or click blank then click option'
Abelongs_with
Bbelongs_to
Chas_one
Dhas_many
Attempts:
3 left
💡 Hint
Common Mistakes
Using has_many instead of belongs_to
Using belongs_with which is not a valid Rails method
2fill in blank
medium

Complete the code to add a foreign key column for the belongs_to association in a Rails migration.

Ruby on Rails
class AddPostRefToComments < ActiveRecord::Migration[7.0]
  def change
    add_reference :comments, :[1], foreign_key: true
  end
end
Drag options to blanks, or click blank then click option'
Acomment
Buser
Carticle
Dpost
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong model name for the foreign key
Forgetting to add foreign_key: true
3fill in blank
hard

Fix the error in the belongs_to association declaration.

Ruby on Rails
class Order < ApplicationRecord
  [1] :customer, optional: true
end
Drag options to blanks, or click blank then click option'
Abelongs_to
Bhas_many
Cbelongs
Dhas_one
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'belongs' instead of 'belongs_to'
Using 'has_many' which is for collections
4fill in blank
hard

Fill both blanks to complete the belongs_to association with a custom class name and foreign key.

Ruby on Rails
class Review < ApplicationRecord
  belongs_to :[1], class_name: '[2]', foreign_key: 'author_id'
end
Drag options to blanks, or click blank then click option'
Aauthor
Buser
CAuthor
DPost
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase for class_name
Mixing up association name and class name
5fill in blank
hard

Fill all three blanks to complete a belongs_to association with a polymorphic interface.

Ruby on Rails
class Picture < ApplicationRecord
  belongs_to :[1], polymorphic: [2], optional: [3]
end
Drag options to blanks, or click blank then click option'
Aimageable
Btrue
C:true
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using string 'true' instead of boolean true
Using string 'false' instead of boolean false
Wrong association name