1

When using location in respond with, it is ignoring validation errors and redirecting to the specified location. Is this expected behavior?

I checked in the responder module that it checking if there are any errors on the model. I inspected the model and it contains validation errors in the @solution object. What am I missing here?

controller:

def create
  @problem = Problem.find(params[:problem_id])
  @solution = @problem.solutions.build params[:solution]
  @solution.save
  respond_with(@solution, :location => detail_problem_solution_path(@problem, @solution)
end

model:

  validates :body, :presence => true, :unless => :reference

reference is true or false false.

chetu
  • 245
  • 3
  • 15
  • Where did you get the reference to use `:location`? It's not in the docs: http://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_with – coreyward Nov 18 '11 at 23:02
  • I found it in several online resources. An example: http://asciicasts.com/episodes/224-controllers-in-rails-3 – chetu Nov 19 '11 at 16:20

2 Answers2

1

I encountered this problem today, and come upon this Rails issue over at github. The exception seems to be thrown since the route url helper can't generate a valid for unsaved (invalid) records.

There's discussion on the github issue about allowing procs as an argument to the location parameter, but it doesn't look like it'll be added anytime soon.

For now I'll stick with using the following solution:

def create
  @post = Post.new(params[:post])
  if @post.save
    respond_with(@post, location: edit_post_path(@post))
  else
    respond_with @post
  end
end
mogelbrod
  • 2,246
  • 19
  • 20
0

The only way I was able to solve is this:

  def create
    @problem = Problem.find(params[:problem_id])
    @solution = @problem.solutions.build solution_params
    success = @solution.save
    respond_with(@solution) do |format|
      format.html {redirect_to detail_problem_solution_path(@problem, @solution) } if success
    end
  end
chetu
  • 245
  • 3
  • 15