我读过the rails tutorial for routing,坦率地说,比我进去时更加困惑。
我通过“rails generate”为我的vanilla rails应用程序生成了新的控制器,我不知道如何正确映射到这些新控制器的索引。我之前得到了它,但它似乎非常hacky所以我要求确认我正在学习正确的东西,而不是'诀窍'让事情发挥作用。
我有几个控制器:
我在主控制器的index.html.haml页面上有一个导航部分来自相关的动作(我认为)。我的问题是,我正在尝试使用link_to
链接到这些新控制器及其各自的索引操作,我收到的错误如下:
ActionController::UrlGenerationError in Home#index
No route matches {:controller=>"sponsors", :action=>"index", :class=>nil}
Trace of template inclusion: app/views/home/index.html.haml
我可以通过向resources :sponsors ...
添加routes.rb
来删除错误,但这是正确的做法吗?我不希望我的控制器索引通过url.com/controller/index
访问,而是url.com/controller
- 到目前为止所有内容都要求我链接到url.com/controller/index
。
我认为我需要:
def index
end
在每个控制器.rb
文件中,但随后出现上述问题。您无法通过输入google.com/index访问google.com,那么如何告诉rails我不希望通过/ index访问我的控制器?我认为这样做的唯一方法是没有
def index
end
在每个控制器.rb
文件中。
KCC::Application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
get "home/index"
# You can have the root of your site routed with "root"
root to: 'home#index'
%li
= link_to "Sponsors", :controller => "sponsors", :action => "index", :class => ( "active" if params[:controller] == "sponsors" )
-#%a{ :href => "/sponsors" } Sponsors
-#= "active" if params[:controller] == "home"
%li
= link_to "Events", :controller => "events", :action => "index", :class => ( "active" if params[:controller] == "events" )
-#%a{ :href => "/events" } Events
%li
= link_to "Committee", :controller => "committee", :action => "index", :class => ( "active" if params[:controller] == "committee" )
-#%a{ :href => "/committee" } Committee
%li
= link_to "Membership", :controller => "pages", :action => "membership", :class => ( "active" if params[:controller] == "pages" )
-#%a{ :href => "/membership" } Membership
%li
= link_to "About", :controller => "pages", :action => "about", :class => ( "active" if params[:controller] == "pages" )
-#%a{ :href => "/about" } About
%li
= link_to "Contact", :controller => "pages", :action => "contact", :class => ( "active" if params[:controller] == "pages" )
-#%a{ :href => "/contact" } Contact
%li#join
= link_to "Join", :controller => "users", :action => "join", :class => ( "active" if params[:controller] == "users" )
-#%a{ :href => "/contact" } Join
%li#signin
= link_to "Sign In", :controller => "users", :action => "signin", :class => ( "active" if params[:controller] == "users" )
-#%a{ :href => "/contact" } Sign In
答案 0 :(得分:1)
必须在routes.rb文件中定义路径,如
get "controller/action"
让我从你的控制器及其动作中再举一个例子。 何时编写任何自定义方法并希望自定义自己的路由而不是任何控制器名称及其操作名称。必须以这种方式定义你的路线
match 'sponser-list' => "sponsors#index", :as => :sponsors ,via: [:get]
这样,没有人可以跟踪你的控制器和动作名称...给我自定义路线名称,因为我向你显示“赞助者列表”。所以你会有
url.com/sponser-list
这可以与任何动作和控制器一起使用。
而且你可以访问。
做rake路线并且你将拥有你的路线,通过在它后面的a _path路径使用它。比如sponsors_path。