Ruby on Rails link_to 语法
在遵循我发现的教程之后。 我现在再次重做,没有脚手架部分,以更好地学习它。
但是,编辑我的 \app\views\home\index.html.erb 以包含:
<h1>Rails test project</h1>
<%= link_to "my blog", posts_path>
我收到错误:
undefined local variable or method `posts_path' for #<ActionView::Base:0x4e1d954>
在执行此操作之前,我运行了 rake db:create,定义了一个迁移类并运行了 < code>rake db:migrate,一切都没有问题。
所以数据库应该包含一个 posts 表。 但是 link_to
命令似乎无法找到 posts_path
。 该变量(或者甚至是一个函数?)可能是通过脚手架例程定义的。
我现在的问题是; 我如何自己手动执行此操作,定义posts_path
?
After following a tutorial Ive 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:
<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.
So the database should contain a posts table. But that link_to
command cant seem to find posts_path
. That variable (or is it even a function?) is probably defined through the scaffold routine.
My question now is; how do I do that manually myself, define posts_path
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在
config/routes.rb
中定义帖子的路径Rails 2.x 语法:
Rails 3.x 语法:
You will need to define a path to your posts in
config/routes.rb
Rails 2.x syntax:
Rails 3.x syntax:
_path 方法通常是动态生成的。 当没有指向指定对象的路由时,或者在这种情况下,没有指向您显式调用的方法时,就会出现方法丢失错误。
定义一条路线应该可以解决这个问题。 上面的 HermanD 展示了一种实现此目的的方法。
您可以从 Rails 应用程序的根目录运行“rake paths”来查看配置的所有路由
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.
Defining a route should fix this. HermanD above showed one way to do this.
You can run 'rake routes' from the root of your rails app to see all the routes that are configured
<%= link_to "my blog", posts_path>
如果这正是您的 erb 所包含的内容,则它缺少 scriptlet 元素末尾的百分号。 不确定这是否导致了你的问题,或者也许我把事情看得太字面意思了......
<%= link_to "my blog", 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....