0

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?

Andrew
  • 227,796
  • 193
  • 515
  • 708
tenaz3.comp
  • 367
  • 6
  • 17

1 Answers1

0

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...

Enders
  • 708
  • 1
  • 4
  • 11
  • I thought just render the main part o web and let rails take care of header and footer. But in my header will be a logout button and when is clicked it'll 'erase' data like current_user that i have in main part. The problem is i don't know how to trigger this button in rails and make backbone listen them to make its actions. Do you have idea? – tenaz3.comp Dec 04 '13 at 03:30
  • Hmm, I can't imagine a use case where it would be useful to delete the user session but and not do a full page reload. Most websites (all?) just reload everything when you sign out (that's what you mean by erasing 'current_user', right?). – Enders Dec 04 '13 at 04:26
  • Yeah, because any data that kept in session should be null after sign out. – tenaz3.comp Dec 04 '13 at 13:34
  • @user2258959 Use a Backbone View to listen to the button click event and perform an `$.ajax(type:'POST', data:{'_method': 'delete')` to log out. – Andrew Oct 06 '14 at 23:26