Search code examples
javascriptruby-on-railsbackbone.jsruby-on-rails-4backbone-rails

backbone-rails: redirection to a controller action


I am using rails-backbone gem for the first time. I have to doubt in how to redirect in using backbone. Following the steps that i followed as provided at github's page and everything is working fine. but when i see my controller it contains the following line in create action

respond_to do |format|
      if @login.save
        format.html { redirect_to @login, notice: 'Post was successfully created.' }
        format.json { render action: 'show', status: :created, location: @login }

which works great but I can see that for json object it renders show action and hence not possible to reload the page as it takes ID as attribute, I can use a static page for display is one solution but i need it to redirect it to show action rather than rendering it as done when the format is html. how can that be done?

This is my complete controller:

class LoginsController < ApplicationController
 before_action :set_login, only: [:show]

  def index
  end

  def new
      @login = Login.new
  end
  def show

  end
    def create
            @login = Login.new(login_params)

    respond_to do |format|
      if @login.save
        format.html { redirect_to @login, notice: 'Post was successfully created.' }
        format.json { render action: 'show', status: :created, location: @login }
      else
        format.html { render action: 'new' }
        format.json { render json: @login.errors, status: :unprocessable_entity }
      end
    end
  end

  private
  def set_login
      @login = Login.find(params[:id])
    end
    def login_params
            params.require(:login).permit(:email, :password)
    end
end

Solution

  • There are many ways to do it. 1)In you controller instead of rendering json object, just create create.js.erb under views/logins then put js code to redirecting the page. It should be something like this,

    create.js.erb:

    window.location.href = <%= users_path(@user) %>
    

    2) You can execute this window redirection js code in the backbone callback after the successfull creation of record. Please refer this backbone affcial website to know how to success callback.