Ruby on rails link_to 语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/545951/
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
Ruby on rails link_to syntax
提问by Mizipzor
After following a tutorialIve found. Im now redoing it again, without the scaffolding part, to learn it better.
按照我发现的教程之后。我现在重做一遍,没有脚手架部分,以便更好地学习。
However, editing my \app\views\home\index.html.erb to contain:
但是,编辑我的 \app\views\home\index.html.erb 以包含:
<h1>Rails test project</h1>
<%= link_to "my blog", posts_path>
I get an error:
我收到一个错误:
undefined local variable or method `posts_path' for #<ActionView::Base:0x4e1d954>
Before I did this, I ran rake db:create, defined a migration class and ran rake db:migrate, everything without a problem.
在我这样做之前,我运行了rake db:create,定义了一个迁移类并运行了rake db:migrate,一切都没有问题。
So the database should contain a posts table. But that link_tocommand cant seem to find posts_path. That variable (or is it even a function?) is probably defined through the scaffold routine.
所以数据库应该包含一个posts表。但是该link_to命令似乎无法找到posts_path. 该变量(或者它甚至是一个函数?)可能是通过脚手架例程定义的。
My question now is; how do I do that manually myself, define posts_path?
我现在的问题是;我如何自己手动完成,定义posts_path?
回答by DanSingerman
You will need to define a path to your posts in config/routes.rb
您需要在 config/routes.rb
Rails 2.x syntax:
Rails 2.x 语法:
map.resources :posts
Rails 3.x syntax:
Rails 3.x 语法:
resources :posts
回答by Kevin Davis
The _path methods are dynamically generated typically. The method missing error comes about when there isn't a route to the object specified or in this case the method you're calling explicitly.
_path 方法通常是动态生成的。当没有指向指定对象的路由或在这种情况下您显式调用的方法时,就会出现方法丢失错误。
Defining a route should fix this. HermanD above showed one way to do this.
定义路线应该可以解决这个问题。上面的 HermanD 展示了一种方法来做到这一点。
You can run 'rake routes' from the root of your rails app to see all the routes that are configured
您可以从 Rails 应用程序的根目录运行 'rake routes' 以查看所有配置的路由
回答by Tom
<%= link_to "my blog", posts_path>
<%= link_to“我的博客”,posts_path>
If this is exactly what your erb contained, it's missing the percent sign at the end of the scriptlet element. Not sure if that caused your problem, or maybe I'm taking things too literally....
如果这正是您的 erb 包含的内容,则缺少 scriptlet 元素末尾的百分号。不确定这是否导致了您的问题,或者我可能把事情从字面上看....

