0
0
Ruby on Railsframework~10 mins

Form object pattern 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 define a form object class inheriting from ActiveModel::Model.

Ruby on Rails
class UserForm
  include [1]

  attr_accessor :name, :email
end
Drag options to blanks, or click blank then click option'
AActiveModel::Model
BActiveRecord::Base
CActionController::Base
DActiveSupport::Concern
Attempts:
3 left
💡 Hint
Common Mistakes
Using ActiveRecord::Base instead of ActiveModel::Model
Forgetting to include any module
2fill in blank
medium

Complete the code to add a validation for presence of :email in the form object.

Ruby on Rails
class UserForm
  include ActiveModel::Model

  attr_accessor :name, :email

  validates :email, [1]: true
end
Drag options to blanks, or click blank then click option'
Auniqueness
Bformat
Cpresence
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length' instead of 'presence' for required fields
Using 'uniqueness' which requires database
3fill in blank
hard

Fix the error in the save method to return false if the form is invalid.

Ruby on Rails
def save
  return false unless [1]
  # persist data here
  true
end
Drag options to blanks, or click blank then click option'
Avalidate
Bsave!
Cvalidates
Dvalid?
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'validate' which runs validations but does not return boolean
Using 'save!' which is for ActiveRecord models
4fill in blank
hard

Fill both blanks to define an initialize method that sets attributes from params hash.

Ruby on Rails
def initialize(params = {})
  params.each do |key, value|
    [1].send("[2]=", value)
  end
end
Drag options to blanks, or click blank then click option'
Aself
Bparams
Ckey
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'params.send' instead of 'self.send'
Using 'value' instead of 'key' for method name
5fill in blank
hard

Fill all three blanks to define a save method that validates, creates a User, and returns true if successful.

Ruby on Rails
def save
  return false unless [1]
  user = User.new(name: [2], email: [3])
  user.save
end
Drag options to blanks, or click blank then click option'
Avalid?
Bname
Cemail
Dsave!
Attempts:
3 left
💡 Hint
Common Mistakes
Calling save! instead of save which raises exceptions
Not checking validity before saving