Ruby on rails link_to syntax

2019-06-16 04:12发布

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?

3条回答
\"骚年 ilove
2楼-- · 2019-06-16 04:27

<%= 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....

查看更多
在下西门庆
3楼-- · 2019-06-16 04:39

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

查看更多
劳资没心,怎么记你
4楼-- · 2019-06-16 04:43

You will need to define a path to your posts in config/routes.rb

Rails 2.x syntax:

map.resources :posts

Rails 3.x syntax:

resources :posts
查看更多
登录 后发表回答