开发者

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)      开发者_如何学Go             {: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.


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.


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜