Forum: Ruby on Rails Respond with JS on create-success, otherwise respond with HTML

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5c17a9b2e2e596b94ea87cc557929124?d=identicon&s=25 why-el (Guest)
on 2013-07-02 16:20
(Received via mailing list)
Hey fellas,

Is there a way to selectively respond with a format depending on whether
there were errors creating an object or not?

My goal is to *have a remote form fall back to the html version of the
'new' action if there were errors*. In other words, run the
create.js.erb
if the save succeeds, otherwise render the html 'new' action.

Say I have the following create method:

  def create
    @message = Message.new(params[:message])

    respond_to do |format|
      if @message.save
      format.html {
        redirect_to messages_path, notice: 'Your message was
successfully
sent.'
      }
      format.js
      else
       render action: "new" # This does not work when I have a remote
form.
      end
    end
  end

This will work fine (On both remote html and js formats ) if the
@message
saves, but when I try and do this using Ajax and they were errors, the
render call responds with html that gets ignored by the browser (who is
expecting js). How can force the browser to render the HTML version of
'new' even if the original action was JS?
5c17a9b2e2e596b94ea87cc557929124?d=identicon&s=25 Mohamed Wael Khobalatte (Guest)
on 2013-07-02 21:47
(Received via mailing list)
Any ideas on this?


On Tue, Jul 2, 2013 at 3:19 PM, why-el <wael.khobalatte@gmail.com>
wrote:

>
>       else
> 'new' even if the original action was JS?
> .
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>



--
Mohamed Wael Khobalatte
This topic is locked and can not be replied to.