2.5 Exercises
Note: To receive a copy of the Solutions Manual for Exercises, with solutions to every exercise in the Ruby on Rails™ Tutorial, visit www.railstutorial.org/<word>, where “<word>” is the last word of the Figure 3.9 caption.
The code in Listing 2.18 shows how to add a validation for the presence of micropost content to ensure that microposts can’t be blank. Verify that you get the screen shown in Figure 2.19.
Figure 2.19 The effect of a micropost presence validation.
Update Listing 2.19 by replacing FILL_IN with the appropriate code to validate the presence of name and email attributes in the User model (Figure 2.20).
Figure 2.20 The effect of presence validations on the User model.
Listing 2.18 Code to validate the presence of micropost content.
app/models/micropost.rb
____________________________________________________________________________
class Micropost < ActiveRecord::Base
belongs_to :user
validates :content, length: { maximum: 140 },
presence: true
end
____________________________________________________________________________
Listing 2.19 Adding presence validations to the User model.
app/models/user.rb
____________________________________________________________________________
class User < ActiveRecord::Base
has_many :microposts
validates FILL_IN, presence: true
validates FILL_IN, presence: true
end
____________________________________________________________________________