user627542
user627542

Reputation:

Rails 3.1 nested forms validation

I'm using Formtastic 2 for a nested form - I have a menus and a meals model, menus have many meals, every meal belongs to one menu. I added the meal form to the menu show action, right below a list of already associated meals.

Creating meals works fine if validation succeeds, I forward to the menu show action again listing the created meal in the list.

But when the meals doesn't get validated and I forward to the menu show action again with an appropriate flash message, I would really like to fill the form with the data that was submitted before and rendering the errors next to it.

I tried with this redirect:

redirect_to(menu_path(menu,@meal), :alert => 'The meal was not created')

But I can't get at the meal variable and passing it back to the form this way, the request itself is a GET request with only the menu id.

Upvotes: 0

Views: 397

Answers (1)

iain
iain

Reputation: 16274

You shouldn't redirect after validation errors, because you'll lose all state. Just the old template directly after a failed validation. A little gotcha is that you need to use flash.now[:alert], so it won't carry over to the next page.

Usually you'll have this structure:

def new
  @meal = Meal.new
end

def create
  @meal = Meal.new(params[:meal])
  if @meal.save
    flash[:notice] = "Meal was created"
    redirect_to menu_path(menu, @meal)
  else
    flash.now[:alert] = "The meal was not created"
    render :new
  end
end

Upvotes: 2

Related Questions