abpetkov
abpetkov

Reputation: 914

Rails: Better syntax for respond_to (shorthand)

I have the following code for the update method of a user settings controller:

def update
  @user = ...
  if @user.update_attributes(params[:user])
    flash[:success] = 'Some success message.'
    respond_to do |format|
      format.html { redirect_to some_path }
      format.js   { head :ok }
    end
  else
    flash[:error] = 'Some error message.'
    render action: 'some action'
  end
end

I'm wondering if there a way to shorten this whole method? Best option would be to reduce the number of lines for the respond_to block, if there's a way to use some shorthand syntax in there.

Upvotes: 1

Views: 450

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

If you're not supporting a js submission you can remove the respond_to block completely. Also, note the use of flash.now which is needed to display a flash message on a render.

def update
  @user = ...
  if @user.update_attributes(params[:user])
    flash[:success] = 'Some success message.'
    redirect_to some_path
  else
    flash.now[:error] = 'Some error message.'
    render action: 'some action'
  end
end

Upvotes: 1

Related Questions