Skip to content

respond_with and Location header for failed 'create' actions #2798

@szimek

Description

@szimek

In my app I've got nested models and when the parent is successfully created, I'm redirecting to its child form. However there's a small problem with specifying :location param for respond_with in create actions like this one:

def create
  @program = Program.new(params[:program])
  @program.save
  respond_with(@program, {:location => new_program_product_path(@program))
end

The problem is that when @program.save fails, @program doesn't have an ID and thus generating the route raises an exception.

I assumed that in this particular case :location param is only used in successful response, as I don't think it really makes sense to return it with failed responses. If that was the case one could modify ActionController::Responder#resource_location to accept procs and they'd be evaluated only when the response is successful and object has an ID.

However, it turns out that Rails sets Location header even for failed responses. It looks like it just sets it always whenever there's a :location param - ActionController::Rendering#_process_options.

I'm not sure if it makes sense, but maybe it could be changed that in case of failed 'create' action Rails would not set Location header (e.g. remove it in ActionController::Responder) and one simply could do:

respond_with(@program, {:location => proc { new_program_product_path(@program) })

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions