Form Objects: Use Reform Gem with User / Pet Example

1.2k Views Asked by At

Nick Sutterer's Reform gem appears to be awesome but for some reason i cannot grok how to apply it to my proof-of-concept Rails app. I have read the docs and a number of blog posts but still do not fully understand how it would work.

Given the following criteria, what would the code for models, form object class, view and controller look like?

  • The app has User and Pet models
  • The signup form accepts a User.email and his Pet.name
  • Users cannot signup without a valid email address
  • When a user signs up the User's account is created and a pet row is created and automatically associated to the user

Sample models:

A user

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :pets
end

His pet

# app/models/pet.rb
class Pet < ActiveRecord::Base
  belongs_to :user
end

Thank you!

1

There are 1 best solutions below

3
On BEST ANSWER
class UserForm < Reform::Form
  property :email

  property :pet, populate_if_empty: Pet do
    property :name
  end
end

You then instantiate the form as follows.

UserForm.new(User.new)

And validation works vice-versa.

UserForm.new(User.new).validate(params[:user])

I recommend you buying the book. This is no covert advertise but I was basically repeating myself here hahaha.