Skip to content

Instantly share code, notes, and snippets.

@teamon
Created October 20, 2012 18:31
Show Gist options
  • Save teamon/3924291 to your computer and use it in GitHub Desktop.
Save teamon/3924291 to your computer and use it in GitHub Desktop.
Custom form models
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
O rly? Duplikacja atrybutów, duplikacja walidacji, pozdro z walidacja typu uniqueness of albo cokolwiek innego co hituje bazy per model.
class SignUpController
def new
@form = SignUpForm.new()
end
def create
@form = SignUpForm.new(params[:sign_up_form])
if @form.valid?
@form.save!
else
render :new
end
end
end
class User
end
class Account
belongs_to :user
end
class Actor
belongs_to :user
belongs_to :actor
end
class SignUpForm
extend ActiveModel::Naming
include ActiveModel::Conversion
attr_reader :user
attr_reader :actor
attr_reader :account
def initialize(attrs = {})
@user = User.new(attrs[:user])
@account = Account.new(attrs[:account])
@account.user = @user
@actor = Actor.new.tap do |a|
a.user = @user
a.account = @account
a.role = "owner"
end
end
def persisted?
false
end
def valid?
[@user, @account, @actor].map(&:valid?).inject(true){|a,b| a && b}
end
def save!
User.transaction do
@user.save!
@account.save!
@actor.save!
end
end
end
= semantic_form_for @form do |f|
= f.fields_for :user, @form.user do |ff|
= ff.input :email
= ff.input :password
= ff.input :password_confirmation
= ff.input :name
= f.fields_for :account, @form.account do |ff|
= ff.input :name, :label => "Account name"
= ff.input :domain
= f.actions do
= f.action :submit, :as => :button, :label => "Sign up"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment