-
Notifications
You must be signed in to change notification settings - Fork 184
Rails Integration
shamanime edited this page Nov 25, 2014
·
5 revisions
Reform makes it very simple to integration into a rails application.
A Sample Rails app using Reform.
It is recommended to create a folder called forms
directly under app to keep form classes organized.
- app
- assets
- controllers
- forms
- helpers
- mailers
- models
- views
If you're using rails 4.0+ anything under /app
will be loaded automatically, otherwise you will need to configure config/application.rb
to load this directory.
module TestApp
class Application < Rails::Application
config.autoload_paths += %W(#{config.root}/forms)
end
end
class UserProfileForm < Reform::Form
include DSL
include Reform::Form::ActiveModel
property :email, on: :user
properties :gender, :age, on: :profile
model :user, on: :user
validates :email, :gender, presence: true
validates :age, numericality: true
end
<%= form_for @form do |f| %>
<%= f.email_field :email %>
<%= f.input :gender %>
<%= f.number_field :age %>
<%= f.submit %>
<% end %>
class UsersController < ApplicationController
def new
@form = create_new_form
end
def edit
@form = create_edit_form
end
def create
@form = create_new_form
if @form.validate(params[:user])
@form.save do |data, map|
new_user = User.new(map[:user])
new_user.build_user_profile(map[:profile])
new_user.save!
end
end
end
def update
@form = create_edit_form
if @form.validate(params[:user])
@form.save do |data, map|
user.update!(map[:user])
user.profile.update!(map[:profile])
end
end
end
private
def user
@user ||= User.find(params[:id])
end
helper_method :user
def create_new_form
UserProfileForm.new(user: User.new, profile: UserProfile.new)
end
def create_edit_form
UserProfileForm.new(user: user, profile: user.profile)
end
end