Toby Joiner
Toby Joiner

Reputation: 4376

How to use routes in .js.coffee script rails

I have this code:

$('#my_form .submit').click( ->
  $.ajax( ->
  type: "post",
  url: "????",
  data: $("#myform").serialize(),
  #success: this.saveUserResponse
)

POST   /schedule_details(.:format)                   {:action=>"create", :controller=>"schedule_details"}

I guess this is 2 questions, or looking for the right way to do it. How can I use a shedule_details_create_path and how can I use that in my javascript? Or, is there a better way to do this?

Thank you for any help.

Upvotes: 1

Views: 3273

Answers (3)

elquimista
elquimista

Reputation: 2271

js-routes gem works great for me.

Gemfile:

gem "js-routes"

Require js routes file in application.js.

//= require js-routes

Flush asset pipeline cache before trying js-routes for the first time and restart your rails server:

rake tmp:cache:clear
rails s

Finally in your coffeescript file:

Routes.users_path()
# => "/users"
Routes.user_path 1
# => "/users/1"
Routes.user_path 1, format: 'json'
# => "/users/1.json"
Routes.user_path 1, anchor: 'profile'
# => "/users/1#profile"
Routes.new_user_project_path 1, format: 'json'
# => "/users/1/projects/new.json"

For advanced configuration, just check js-routes github repo.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039080

How about unobtrusively AJAXify the form instead of subscribing for the click handler of the submit button:

$('#my_form').submit(function() {
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize(),
        success: this.saveUserResponse
    });
    return false;
});

This way you can generate the form using the routing and have its action attribute properly set in the markup. Then your javascript is completely independent.

Upvotes: 4

Cygnusx1
Cygnusx1

Reputation: 5409

in your routes.rb you can write something like that:

match "/schedule_details/create" => "schedule_details#create"

and put /schedule_details/create in the url: param of your ajax call.

Hope i understood your need!

Upvotes: 0

Related Questions