link_to机制如何在Ruby on Rails中运行
我根据给出的指示实现了官方创建博客应用程序项目。 但我不知道在这个项目中使用的link_to
的想法如下:
'Are you sure?', :method => :delete %>
在app/views/posts/index.html.erb
文件中给出, app/controllers/posts_controller.rb
相应代码用于在app/views/posts/
目录中呈现html页面。
如果我想渲染一个新的html页面,请说app/views/posts/
目录中的index2.html.erb
与index.html.erb
相比没有’Edit’和’Destroy’链接,那么我应该如何编写link_to
和posts_controller.rb
相应代码?
如果你想要一个名为index2
的动作,比如http://localhost:3000/posts/index2
这样的示例url,那么你需要:
-
在
posts_controller.rb
为它创建一个动作(方法):class PostsController < ApplicationController ... def index2 end ... end
-
在
app/views
目录中index2.html.erb
创建一个名为index2.html.erb
的视图文件 -
添加到
config/routes.rb
的路由,例如:resources :posts do member do get 'index2' end end
要链接到新创建的index2
页面,请在其他html.erb
文件中添加一个链接,如下所示:
link_to "index 2",index2_post_path
我强烈推荐使用Rails的Agile Web Development(实用程序员)
通过在post_controller.rb中编写link_to和相应的代码,不确定你究竟是什么意思
link_to机制可以简化如下:
link_to('whatever you want to display in the link',{:controller => 'corresponding controller name',:action => 'corresponding action name'})
就渲染不同的模板而言,只需转到控制器并写下:
渲染( ‘controllername /视图’)
希望这会有所帮助