Skip to content

Instantly share code, notes, and snippets.

@thehenster
Last active November 16, 2015 16:18
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 thehenster/723576a5db6711d07724 to your computer and use it in GitHub Desktop.
Save thehenster/723576a5db6711d07724 to your computer and use it in GitHub Desktop.
Pattern for Form Objects in Rails
class RecipeForm
ATTRIBUTES = [:name, :cooking_time_minutes]
attr_reader :recipe
attr_accessor *ATTRIBUTES
def initialize(recipe)
@recipe = recipe
end
def assign_attributes(attributes)
attributes.each do |k,v|
send("#{attribute}=", v)
end
end
def save
ATTRIBUTES.each do |attribute|
recipe.public_send("#{attribute}=", send(attribute))
end
recipe.save
end
end
class RecipesController < ApplicationController
def create
@recipe_form = RecipeForm.new(Recipe.new)
@recipe_form.assign_attributes(recipe_params)
if @recipe_form.save
redirect_to recipes_path
else
render :new
end
end
def update
recipe = Recipe.find(params[:id])
@recipe_form = RecipeForm.new(recipe)
if @recipe_form.update
redirect_to recipes_path
else
render :edit
end
end
private
def recipe_params
params.require(:recipe).permit(:name, :cooking_time_minutes)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment