views:

53

answers:

1

(Rails newbie)

Hello!

I am feeling like I am reusing a lot of my code and I feel there has to be a better way to do this... (I am sure there is...)

What I have is a Settings page, where you can create categories and procedures (which belong to a category).

index Settings action:

def categories_and_procedures   
    @prefs = @current_practice.preferences

    @category = @current_practice.categories.build
    @categories = @current_practice.categories.all
    @procedure = @current_practice.procedures.build
end

In the view is a list with all the current categories and a form to create a new one. In the Category model is a validation (validates_uniqueness_of :name).

The create action:

    def create_category
    @category = @current_practice.categories.build(params[:category])
    if @category.save
        flash[:notice] = "New category created: <i>#{@category.name}</i>"
        redirect_to :action => "categories_and_procedures"
    else
        ##Duplicate code!!!!!!
        @prefs = @current_practice.preferences

        @category = @current_practice.categories.build
        @categories = @current_practice.categories.all
        @procedure = @current_practice.procedures.build
        ##Duplicate code!!!!!!
        render :action => "categories_and_procedures"
    end
end

Is there a way I can move it to a function I can call? Helper? Filters? I don't know.

Thank you!

+1  A: 

Just write:

def create_category
  @category = @current_practice.categories.build(params[:category])
  if @category.save
    flash[:notice] = "New category created: <i>#{@category.name}</i>"
    redirect_to :action => "categories_and_procedures"
  else
    categories_and_procedures
    render :action => "categories_and_procedures"
  end
end

It will look better if you will add some setup method:

def setup_object
  @prefs = @current_practice.preferences

  @category = @current_practice.categories.build
  @categories = @current_practice.categories.all
  @procedure = @current_practice.procedures.build
end

and call it from categories_and_procedures and from create_category.

klew
Ah thanks! I tried it and once i pressed submit nothing happend (when I was expecting errors). I think the @category = @current_practice.categories.build was replacing the errors. But when I use a set_up method i can just leave that out and put it in the "categories_and_procedures" separately. Thanks again!
Macint