【问题标题】:Ruby on rails routing is displaying only show view for index and edit action methodsRuby on rails 路由仅显示索引和编辑操作方法的显示视图
【发布时间】:2015-07-11 05:58:39
【问题描述】:

我创建了一个控制器并添加了默认的 7 个操作方法,我还创建了 4 个视图,它们是 index 、 new 、 show 、 edit 都包含不同的数据

also added resources :posts controller configuration into my routing file as well 
'
My problem is when i try to navigate to index or edit views using url .. it displays me only show views , however index method is working as a default 

below are my urls `enter code here`

1 . http://localhost:3000/posts/index[^]

如果我尝试这个,它会给我显示视图数据

  1. localhost:3000/帖子

这给了我正确的索引数据(默认不提及索引操作名称)

  1. http://localhost:3000/posts/edit[^]

这个但总是向我显示显示视图中存在的数据,而不是编辑视图中存在的数据

请推荐

下面是我的路由文件中的几行。

Hide   Copy Code
Rails.application.routes.draw do
  get 'home/index'
  resources :posts

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'home#index'

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    请阅读Rails guide entry on default resource routing,这里没有什么异常情况。

    /posts 是您访问posts#index 的方式,而不是/posts/index

    对于显示和编辑,您需要在 URL 中添加您的帖子 ID,以便 Rails 知道要检索哪条记录,即/posts/1/edit

    【讨论】:

    • 好的,谢谢。我明白了。但是我有一个疑问,为什么 /posts/index 或 /posts/edit 正在导航我以显示视图。安装它应该找不到资源错误,就像 asp.net mvc 一样,'实际上我是 ruby​​ on rails 的新手,并试图理解这背后的一些概念
    • 取决于控制器的显示动作。获取资源的代码是什么?如果它类似于 @post = Post.find(params [:id]) 那么是的,你应该得到一个错误(除非你有一个 id 为“edit”的帖子:p)
    【解决方案2】:

    您可以从控制台运行rake routes 来查看您的所有路线。 resources :posts的结果应该是以下7条路由:

        Prefix Verb   URI Pattern               Controller#Action
               POST   /posts(.:format)          posts#create
     new_sheet GET    /posts/new(.:format)      posts#new
    edit_sheet GET    /posts/:id/edit(.:format) posts#edit
         sheet GET    /posts/:id(.:format)      posts#show
               PATCH  /posts/:id(.:format)      posts#update
               PUT    /posts/:id(.:format)      posts#update
               DELETE /posts/:id(.:format)      posts#destroy
    

    Rails 会将 URL 与 URI 模式匹配,并采取匹配的控制器操作。顺便说一句,您可以使用rake routes CONTROLLER=posts 来查看posts 的路线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      相关资源
      最近更新 更多