-
-
Save jandudulski/3924370 to your computer and use it in GitHub Desktop.
Custom form models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
= 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