Javascript 在javascript中访问rails路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3257818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing rails routes in javascript
提问by kishore
Can anyone explain how i can access the rails routes/names routes in javascript ?
谁能解释我如何在 javascript 中访问 rails 路由/名称路由?
The following are some of the things i tried http://github.com/jsierles/js_named_routes.
以下是我尝试过的一些事情 http://github.com/jsierles/js_named_routes。
but no luck.
但没有运气。
回答by Bogdan Gusiev
I was researching this question for a while and didn't found any implementation compatible with Rails 3.
我研究了这个问题一段时间,并没有发现任何与 Rails 3 兼容的实现。
So decided to write my own:
所以决定自己写:
回答by rapofran
kishore I think this is the simpliest way, just call:
kishore 我认为这是最简单的方法,只需调用:
Rails.application.routes.url_helpers.*_path
Rails.application.routes.url_helpers.*_path
So, if you have in your routes.rb, let's say:
所以,如果你在你的 routes.rb 中有,让我们说:
resources :users
资源:用户
then you want to call the index action from a javascript file, you do:
那么你想从一个 javascript 文件中调用 index 动作,你可以:
$.get('<%= Rails.application.routes.url_helpers.users_path %>', function(data){ ...
Take into account that the js file should have a .erb extension (or *.js.erb) so rails knows that must be preprocessed. Otherwise, the file will be served as is.
考虑到 js 文件应该有一个 .erb 扩展名(或 *.js.erb),因此 Rails 知道必须对其进行预处理。否则,文件将按原样提供。
回答by bjg
If I understand your requirement correctly you want Javascript code in your views to have access to the named routes. If so, then one simple way to do this is to render your Javascript code through a template (ERB, Haml, etc) and then to expand the routes something like the following:
如果我正确理解您的要求,您希望视图中的 Javascript 代码能够访问命名路由。如果是这样,那么一种简单的方法是通过模板(ERB、Haml 等)呈现您的 Javascript 代码,然后扩展路由,如下所示:
ERB:
再培训局:
<script>
$.get('<%= some_named_route_path %>', function(data) {
});
</script>
Haml:
哈姆:
:javascript
$.get('#{ some_named_route_path }', function(data) {
});
UPDATE: Adding suggestions for public/javascripts/case
更新:添加public/javascripts/案例建议
Accessing named routes from the public folder is a bit trickier but there at least 2 ways that come to mind, neither of which is entirely satisfactory but, one or either of which might suit your application
从公共文件夹访问命名路由有点棘手,但至少有两种方法可以想到,这两种方法都不完全令人满意,但其中一种或其中一种可能适合您的应用程序
- Create javascript templates in (say)
lib/javascriptsusing ERB named like'*.js.erb'and araketask to expand those templates intopublic/javascripts before deploying (say as a step in your Capistrano recipe for example). Downside of that is that your changes are not made available live on the site until the templates are expanded and you might not get the right syntax highlighting of your javascript with an.erbextension file - Create per-view javascript helper functions in a
content_for :headblock which expand the named routes and make those available to code from your public javascript files. If you're careful with namespacing and conventions this might work out well. The downside is that the code calling these javascript helpers is decoupled from the code that defines them which could be confusing for maintainers or prone to abuse.
- 在(例如)
lib/javascripts使用名为 like 的 ERB创建 javascript 模板,'*.js.erb'以及在部署之前将rake这些模板扩展为public/javascripts的任务(例如,作为您 Capistrano 配方中的一个步骤)。不利的一面是,在扩展模板之前,您的更改不会在网站上实时可用,并且您可能无法使用.erb扩展文件对 javascript 进行正确的语法突出显示 - 在一个
content_for :head块中创建每个视图的 javascript 帮助函数,该函数扩展命名路由并使这些路由可用于从您的公共 javascript 文件中进行编码。如果您对命名空间和约定很小心,这可能会很好。缺点是调用这些 javascript 助手的代码与定义它们的代码分离,这可能会使维护人员感到困惑或容易被滥用。
In some view:
在某些方面:
<% content_for :head do %>
<script>
SomeNameSpace.helper_to_some_named_route = function() {
return '%<= some_named_route_path %>
};
</script>
<% end %>
Then in public/application.js(say)
然后在public/application.js(说)
$.get(SomeNameSpace.helper_to_some_named_route(), function(data) {
});
回答by Teemu Leisti
bjg really answered this, but I thought I'd extract the relevant part and amplify with an example.
bjg 真的回答了这个问题,但我想我会提取相关部分并用一个例子来放大。
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:
您只需为您的视图提供一个字符串变量,其值为一个命名的 Rails 路径,然后在表单的 Javascript 中使用该值。一个示例说明了控制器方法如何指定另一种方法的路径,以便在按下按钮时由脚本打开:
File config/routes.rb:
文件config/routes.rb:
...
resource :foo, :only => [:show, :reset]
...
match 'foo_reset_path' => 'foo#reset'
Commanding rake routeswill now produce, among other output, this:
命令rake routes现在将产生,除其他输出外,如下:
foo GET /foo(.:format) foo#show
foo_reset_path /foo_reset_path(.:format) foo#reset
foo_reset_pathis what we're going to use here, but you can of course use this method with any named Rails path.
foo_reset_path是我们将在此处使用的,但您当然可以将此方法用于任何命名的 Rails 路径。
File app/controllers/foo_controller.rb:
文件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:
文件app/views/foo/show.html.erb:
...
<input type="hidden" id="reset_path" name="reset_path" value="<%= @reset_path %>">
...
<script>
$(document).ready(function() {
...
/* Hang functionality on the "Reset form" button. */
$('#reset_button').click(function () {
var reset_path = $('#reset_path').val();
window.open(reset_path, "_self")
});
...
})
</script>
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 resetmethod of foo_controllerto be called.
我在这里使用 JQuery,但基本思想应该很清楚。该脚本为 id 为 的按钮元素添加了一个钩子reset_button,以便单击按钮会调用的reset方法foo_controller。
回答by jakeforaker
What I did based on Teemu's great answer:
我根据 Teemu 的精彩回答做了什么:
In your controller:
在您的控制器中:
def show
@section = Section.find(params[:id])
respond_to do |format|
format.html
format.json { render json: @section}
end
end
In your view:
在您看来:
<input type="hidden" id="section_path" data-path="<%= @section.id %>" name="section_path" value="foo">
In your js:
在你的js中:
var id = $('#section_path').attr('data-path');
$.ajax({
url:'/sections/'+ id +'.json',
type:"GET",
success: function (data){
console.info(data);
},
error: function (xhr, status){
console.info(xhr.error);
}
});
回答by Andrew Burns
See http://tore.darell.no/pages/javascript_routes:
见http://tore.darell.no/pages/javascript_routes:
JavascriptRoutes converts your Rails routes into JavaScript. You can then access (generate) them in the browser (or any other JS environment). It supports both normal and named routes, and creates helper functions for the latter.
JavascriptRoutes 将您的 Rails 路由转换为 JavaScript。然后您可以在浏览器(或任何其他 JS 环境)中访问(生成)它们。它支持普通路由和命名路由,并为后者创建辅助函数。
Update: It looks as though someone has forked this if you prefer jQuery: https://github.com/ajnsit/javascript_routes
更新:如果您更喜欢 jQuery,似乎有人已经分叉了这个:https: //github.com/ajnsit/javascript_routes
回答by user2613844
- gem install the "angular_rails_templates"
- Create a file called angular_rails_templates.rb in the config/initializers folder
- copy following code in the file and restart server. (including "module CustomERBEngine" for it cannot be added to code block by 4 space)
- gem 安装“angular_rails_templates”
- 在 config/initializers 文件夹中创建一个名为 angular_rails_templates.rb 的文件
- 将以下代码复制到文件中并重新启动服务器。(包括“模块CustomERBEngine”,因为它不能以4个空格添加到代码块中)
module CustomERBEngine
module CustomERBEngine
class ERBTemplate < Tilt::ERBTemplate
def evaluate(scope, locals, &block)
scope.class_eval do
include Rails.application.routes.url_helpers
include Rails.application.routes.mounted_helpers
include ActionView::Helpers
end
super
end
end
end
Tilt.register CustomERBEngine::ERBTemplate, '.erb'

