How to use Rails routes and helpers in Backbone?

437 Views Asked by At

I want to use Devise helpers and routes in my Backbone.js code:

user_signed_in?  
user_omniauth_authorize_path(:provider)
destroy_user_session_path, method: :delete

Normally, in my Rails views I can do:

<% if user_signed_in? %>
  <li><%= link_to current_user.name, root_path %></li>
  <li><%= link_to 'Logout', destroy_user_session_path, method: :delete %> </li>
<% else %>
  <%= link_to "Sign in with provider", user_omniauth_authorize_path(:provider) %>
<% end %>

How can I use these routes and helpers in my index.jst.eco Backbone.js template?

1

There are 1 best solutions below

4
On

For the rails route, we use:

gem "js-routes"

Then in your JS, you will get a global object Routes with methods for each of the routes defined in your routes.rb, for instance:

Routes.user_session_path()

It also works with complex paths

Routes.product_attachment_path(2,3)
=> "/products/2/attachments/3"

Or more relevant to you, omniauth paths...

Routes.user_omniauth_authorize_path("linkedin")
=> "/users/auth/linkedin"

This will only give you the urls, but it's a start. For instance, to emulate the link_to with method: delete, you can use a form and use the hidden field _method:

<input type="hidden" name="_method" value="delete"/>

If you combine this with Routes.destroy_user_session_path() (for the URL of the form), you'll have replicated what you could do in one line in your ERB templates!

Just a thought tho, maybe for those stuff (dealing with devise/users), you could let Rails generate the templates? You can always use backbone/jquery to fetch full HTML pages and render them somehwere...