0

I have an issue with a form sendind two parameters to a controller. I would like that the erb.jstemplate not be triggered if the update of the object fails.

I have added return at the end of my action but the view is still triggered.

Her is the bit of my controller which I think is responsible for actionning the view or not :

if @object.update(some_params)

...
  respond_to do |f|
    f.html {redirect_to some_path_here}
    f.js
  end
end

return
Maxence
  • 2,029
  • 4
  • 18
  • 37

1 Answers1

1

That's happens, because according to convention over configuration Rails automatically renders action view, if not explicitly specified.

In order to avoid rendering, one of the options would be setting head if @object hasn't been successfully updated:

if @object.update(some_params)

...
  respond_to do |f|
    f.html {redirect_to some_path_here}
    f.js
  end
else
  head :unprocessable_entity
end
Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53
  • Actually inside the `if` statement the view is rendered correctly. It's outside the condition that the `return` is not really effective. Unfortunately changing the `respond_to` method as you suggest has no effect. (actually I want that the view not to be rendered by default, only if the condition statement is successful.... Maybe it's not a good design) – Maxence Aug 05 '18 at 18:42
  • @Maxence ah, didn't understand your purpose. then you can specify `head` instead of the `return` keyword, that you've tried. updated my answer – Igor Drozdov Aug 05 '18 at 18:45
  • Thanks for this. But now view is not rendered but it is not rendered either if the condition is true (and `update` of object pass). Maybe I should render the view explicitly in the `respond_to` and add `and return` ? (sorry not very familiar with `head` method) – Maxence Aug 05 '18 at 18:48
  • Thanks, works like a charm. Though why `return` didn't work and have to play with head ? – Maxence Aug 05 '18 at 18:53
  • the link, I've provided, actually explains it https://guides.rubyonrails.org/layouts_and_rendering.html#rendering-by-default-convention-over-configuration-in-action – Igor Drozdov Aug 05 '18 at 18:54
  • you need either explicitly render a view (or specify head without content) or let Rails to render it according to the convention – Igor Drozdov Aug 05 '18 at 18:55