Accessing rails routes in javascript

后端 未结 8 1686
星月不相逢
星月不相逢 2020-12-08 19:39

Can anyone explain how i can access the rails routes/names routes in javascript ?

The following are some of the things i tried http://github.com/jsierles/js_named_r

8条回答
  •  醉酒成梦
    2020-12-08 20:33

    bjg really answered this, but I thought I'd extract the relevant part and amplify with an example.

    You simply provide your view a string variable whose value is a named Rails path, and then use that value in the Javascript of your form. An example that illustrates how a controller method can specify the path for another method, to be opened by the script on the press of a button:

    File config/routes.rb:

    ...
    resource :foo, :only => [:show, :reset]
    ...
    match 'foo_reset_path' => 'foo#reset'
    

    Commanding rake routes will now produce, among other output, this:

    foo             GET  /foo(.:format)            foo#show
    foo_reset_path       /foo_reset_path(.:format) foo#reset
    

    foo_reset_path is what we're going to use here, but you can of course use this method with any named Rails path.

    File app/controllers/foo_controller.rb:

    ...
    def show
      @reset_path = "foo_reset_path" # simply the string you'd use in the
                                     # Rails code for opening the path
      ...
    end
    ...
    def reset
      ... # reset some variables to their default values
      redirect_to foo_path # causes the show method to be called, and the HTML
                           # page to be redisplayed
    end
    

    File app/views/foo/show.html.erb:

    ...
    
    ...
    
    

    I'm using JQuery here, but the basic idea should be clear. The script adds a hook to the button element whose id is reset_button, so that clicking on the button causes the reset method of foo_controller to be called.

提交回复
热议问题