ruby-on-railsrubyformsreform

Form Objects: Use Reform Gem with User / Pet Example


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?

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!


Solution

  • 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.