My application currently handles HTML requests only and I would like to extend some actions to also handle JSON requests. Many of the controller actions perform redirects, set session values (flash) depending on whether the request was successful.
How can I incorporate responds_to to change action behavior based on request format for an action such as this:
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = {:success => "User Created."}
session[:user_id] = @user.id
session[:username] = @user.username
redirect_to(:controller => 'lists', :action => 'index')
else
flash[:notice] = {:error => @user.errors}
render('new')
end
end
So as you can see I am checking to see if the model is persisted and then either redirecting or rendering the form again. How can I maintain this current behavior but also handle requests in JSON? JSON requests will not need to perform redirects etc.
Thanks!
This seems to do the trick: