daniel barrera
daniel barrera

Reputation: 367

How render to another view other than the default view

I need the block respond_to not render to new.html.erb if not a another view created by me called for example new_form.html.erb

def new
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @user }
    end
  end

Upvotes: 2

Views: 891

Answers (2)

Milind
Milind

Reputation: 5112

There are many ways to do it....

##FOR HTML CALLS
 format.html { render 'new'}
 format.html { render 'shared/new'}

##FOR JS CALLS
 format.js { render 'new'}
 format.js { render 'shared/new'}
 ##pass variable to the view
 format.js { render 'shared/new',:locals=>{:type=>"User"}}


##OR you can also try redirect in some rare cases WITHOUT respond_to block
redirect_to users_path(params[:id])

Upvotes: 1

NM Pennypacker
NM Pennypacker

Reputation: 6942

Pretty simple. As long as the view is in the default directory for the controller:

respond_to do |format|
  format.html render 'new'
  format.json { render json: @user }
end

If not, you need to tell it which directory:

respond_to do |format|
  format.html render 'users/new'
  format.json { render json: @user }
end

More docs here: http://guides.rubyonrails.org/layouts_and_rendering.html

Upvotes: 3

Related Questions