Given a Rails form object that validates presence of a user's email and password, what will be the state of the form object after calling valid? with missing email?
class UserForm include ActiveModel::Model attr_accessor :email, :password validates :email, presence: true validates :password, presence: true end form = UserForm.new(email: nil, password: 'secret') form.valid?
Think about how ActiveModel::Model validations work when required attributes are missing.
The form object uses ActiveModel validations. Since email is missing, valid? returns false and errors include a message about email presence.
user.name after form submission?Consider a form object that assigns attributes to a User model on save. After calling form.save with name 'Alice', what is the value of user.name?
class UserForm include ActiveModel::Model attr_accessor :name, :user def save return false unless valid? user.name = name true end end user = User.new(name: 'Bob') form = UserForm.new(name: 'Alice', user: user) form.save user.name
Remember the form object assigns the name attribute to the user on successful save.
After form.save, the user's name is updated to 'Alice' because the form object assigns it before returning true.
Which code snippet correctly implements a Rails form object that accepts nested attributes for an associated Profile model?
Remember that accepts_nested_attributes_for is a model method, not available in plain form objects.
Option D manually builds a new Profile with the nested attributes and assigns it to the user before saving. This is the correct way in a form object without model callbacks.
Given the following form object, why does this form object fail to persist the user even when valid data is provided?
class UserForm include ActiveModel::Model attr_accessor :email, :user validates :email, presence: true def save return false unless valid? user.email = email end end user = User.new form = UserForm.new(email: 'test@example.com', user: user) form.save
Check if the user model is saved to the database after assignment.
The form object assigns the email to the user but never calls user.save. Without saving, changes are not persisted.
Why would a developer choose to use a form object instead of directly using ActiveRecord models in a Rails application?
Think about how form objects help manage complexity in large applications.
Form objects encapsulate form-specific validations and logic separate from database models, making code cleaner and easier to maintain and test.