Skip to content

Instantly share code, notes, and snippets.

@agius
Created April 18, 2015 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agius/5c6c64a60e093840739b to your computer and use it in GitHub Desktop.
Save agius/5c6c64a60e093840739b to your computer and use it in GitHub Desktop.
Sometimes, controllers just suck. Time to extract.
class MyController < ApplicationController
def create
@model = Model.new(model_params)
# we have to call this here, to populate
# errors on any other fields that might
# be invalid
@model.valid?
if @model.model_attr == 'invalid' && !@model.in_state(:dont_care)
@model.errors.add(:model_attr, :invalid)
end
if @model.other_attr == 'what is this i am not good with computer' &&
!controller_derived_list.include?(@model.yet_anoth_attr) &&
!plz_stop_conditionals
@models.errors.add(:oh_god, :why)
elsif @conditional
redirect_to other_place, error: "noooooo #{@model.errors.full_messages.join}"
end
# have to use this, since #valid? clears errors
if @model.errors.any?
render 'new' and return
end
elsif @model.save
if params[:notice_one]
flash[:notice] = "2 many conditionals"
else
flash[:notice] = "fail"
end
redirect_to next_path, notice: "you have no idea how many if statements just went right"
else
render 'new'
end
end
private
def model_params
params.require(:model).permit(:attr1, :attr2,
submodel: [:name, {this_doesnt: :work}],
associated_ids: [] # wat
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment