Last active
          November 16, 2015 16:18 
        
      - 
      
- 
        Save thehenster/723576a5db6711d07724 to your computer and use it in GitHub Desktop. 
    Pattern for Form Objects in Rails
  
        
  
    
      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 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 | 
  
    
      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 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