Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

My recipes model is as follows

has_many :quantities
has_many :ingredients, :through => :quantities, :uniq => true
has_many :sizes, :through => :quantities, :uniq => true

And the controller action im trying to refactor

class Admin::QuantitiesController < Admin::AdminController
  layout 'admin'

  authorize_resource :class => :controller

  def create
    recipe        = Recipe.find(params[:recipe_id])
    values      = params[:quantity][:ingredient]
    @quantities = Quantity.find(values.keys)

    @quantities_errors = {}
    @quantities.each do |quantity|
        if quantity.value != values[quantity.id.to_s]
            quantity.value = values[quantity.id.to_s]
            if quantity.valid?
                quantity.save
            else
                @quantities_errors[quantity.id] = quantity.errors.messages
            end
        end
    end

    unless @quantities_errors
        redirect_to edit_admin_recipe_path(recipe), notice: 'Ingredients was successfully added.'
    else
        redirect_to edit_admin_recipe_path(recipe), alert: @quantities_errors
    end

  end

end
share|improve this question
    
This is confusing. You are editing a recipe, right? (edit_admin_recipe_path), then why are you getting the POST in QuantitiesController#create? It should be in RecipesController#update and use Rails infrastructure (mainly accepts_nested_attributes_for), to remove all this boilerplate. –  tokland Jan 26 '13 at 13:39
    
Thanks ever so much, after your comment I found railscasts.com/episodes/196-nested-model-form-part-1 and managed to get it posting to the recipe model and using accepts_nested_attributes_for. I knew the code was dodgy hence why I posted. I didn't know about accepts_nested_attributes_for before now. –  Karl Entwistle Jan 27 '13 at 18:52
    
great, I'll add it as an answer then. –  tokland Jan 27 '13 at 19:52
add comment

1 Answer 1

up vote 0 down vote accepted

Some notes:

  • This is a edit_admin_recipe form, so you should POST to Admin::RecipesController#update.

  • Use Rails infrastructure for the models (accepts_nested_attributes_for) to save nested data. Controllers must be kept simple and clean.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.