简体   繁体   English

Ruby on rails link_to语法

[英]Ruby on rails link_to syntax

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: 但是,编辑我的\\ 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. 所以数据库应该包含一个posts表。 But that link_to command cant seem to find posts_path . 但是link_to命令似乎无法找到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 ? 我如何自己手动完成,定义posts_path

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

<%= 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. 如果这正是你的erb所包含的内容,那么它将缺少scriptlet元素末尾的百分号。 Not sure if that caused your problem, or maybe I'm taking things too literally.... 不确定这是否会导致你的问题,或者我可能太过于字面意思......

The _path methods are dynamically generated typically. _path方法通常是动态生成的。 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. 上面的HermanD显示了一种方法。

You can run 'rake routes' from the root of your rails app to see all the routes that are configured 您可以从rails应用程序的根目录运行“rake routes”以查看配置的所有路由

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM