繁体   English   中英

Rails路由问题,无法找出链接路径

[英]Rails routing issue, can't figure out the link path

让我从一开始就公平,并告诉您我已经“解决”了我描述的问题。 但是您不了解的解决方案并不是真正的解决方案,是吗?

我有资源,新闻快讯。 我有一个Newsbites的索引页。 我所有的CRUD动作均正常。

我创建了一个单独的索引( frontindex.html.erb ),用作我网站的首页,以显示最新的新闻快讯。 格式与我的常规索引不同,因此读者可以获得更大的照片,更多的文章文字(也包括更多广告:)。

在我的路由表中,我有以下语句:

 resources :newsbites
 get 'newsbites/frontindex'
 root 'newsbites#frontindex'

耙路显示以下内容:

newsbites_frontindex GET    /newsbites/frontindex(.:format)   newsbites#frontindex

如果我从根目录(localhost:3000)加载网站,则效果很好。 顶部呈现了一个单独的菜单页面,并且可以正常加载。 我可以单击除“ Home ”链接以外的所有链接,它们可以正常工作。

“主页”链接为:

 <%= link_to 'Home', newsbites_frontindex_path %>

当我单击链接时,出现以下错误:

Couldn't find Newsbite with 'id'=frontindex

错误指向我的Newbites控制器的' show '操作。 这是frontindex并显示控制器的def。 它们的显示方式与我发布它们的方式完全相同:

  def frontindex
  @newsbites = Newsbite.all
  end


  def show
   @newsbite = Newsbite.find(params[:id])
  end

我不明白 当同时具有def和视图时,为什么newbites_frontindex_path调用show动作? 现在,我可以通过简单地指向root_path来解决此问题。 但这并不能帮助我理解。 如果这不是网站的根目录怎么办?

任何帮助将不胜感激。

实际上,我很惊讶您的代码完全奏效。 一条路线必须定义两件事

  • 某种正则表达式的针对该用户的URL匹配( newsbites/frontindex比不同newsbites/backindex
  • 您要为给定的URL做些什么? 您要指向控制器动作

Rails通常不会“猜测”该动作是什么。 或者,也许他仍然能够“猜测”您想使用newsbites控制器,但是这次没有猜测到正确的动作:(。

您应该这样声明根,这就是您所做的

root 'controller#action'

对于其余部分,有两种声明方法。 我喜欢第二个

resources :newsbites
get 'newsbites/frontindex', to: 'newsbites#frontindex'

resources :newsbites do
  # stuff added here will have the context of the `newsbites` controller already
  get 'frontindex', on: :collection # the name of the action is inferred to be `frontindex`
end

on: :collection表示'frontindex'是涉及所有新闻比特的动作,因此生成的URL将是newsbites/frontindex

另一方面get 'custom_action', on: :member意味着该newsbites/:id/custom_action以特定项目为目标,生成的URL看起来像newsbites/:id/custom_action

编辑 :Rails还基于路线声明生成path_helpers

get 'test', to: 'newsbites#frontindex'
get 'test/something', to: 'newsbites#frontindex'
resources :newsbites do
      get 'frontindex', on: :collection
      get 'custom_action', on: :member

将生成路径助手

test_path
test_something_path
# CRUD helpers : new/edit/show/delete, etc. helpers
frontindex_newsbites_path
custom_actions_newsbite_path(ID) # without s !

您始终可以通过添加as:选项来覆盖它

get 'custom_action', on: :member, as: 'something_cool'
# => something_cool_newsbites_path

Rails路线认为frontindex是一个id。 这就是错误消息的内容。 所以,去GET newsbite/:id映射到show

您需要找到一种使Rails路由知道frontindex不是id

附带说明:定义路线的顺序很重要。 将使用第一个匹配的内容。 如果您具有GET newsbite/:idGET newsbite/frontindex ,则将首先出现的那个匹配。 在您的情况下,这是第一个。 也许尝试更改顺序。

暂无
暂无

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

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