轨道路径没有给我路线匹配,但我不明白为什么



所以我有一个非常简单的布局。我的配置路由是:

  resources :webcomics
  match '/webcomics/first' => 'webcomics#first', :as => :first
  match '/webcomics/random' => 'webcomics#random', :as => :random
  match '/webcomics/latest' => 'webcomics#latest', :as => :latest

控制器:

  def show
    @webcomic = Webcomic.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @webcomic }
    end
  end
  def first
    @webcomic = Webcomic.order("created_at ASC").first
    respond_to do |format|
      format.html { render 'show'}
      format.json { render json: @webcomic }
    end
  end
导航栏:

<%= link_to first_webcomics_path, :rel => "tooltip", :title => "first comic" do %>
              formatting in here
        <% end %>

当我点击这个链接时,它首先把我送到正确的路径/webcomics/,但是它给了我错误

Routing Error
No route matches {:action=>"edit", :controller=>"webcomics"}

我要打破我的头怎么去"编辑",不管这个消息是完全错误的,我确实有编辑,但为什么它试图去操作编辑。

def edit
    @webcomic = Webcomic.find(params[:id])
end

rake路由结果:

 first_webcomics GET    /webcomics/first(.:format)    webcomics#first
latest_webcomics GET    /webcomics/latest(.:format)   webcomics#latest
random_webcomics GET    /webcomics/random(.:format)   webcomics#random
       webcomics GET    /webcomics(.:format)          webcomics#index
                 POST   /webcomics(.:format)          webcomics#create
    new_webcomic GET    /webcomics/new(.:format)      webcomics#new
   edit_webcomic GET    /webcomics/:id/edit(.:format) webcomics#edit
        webcomic GET    /webcomics/:id(.:format)      webcomics#show
                 PUT    /webcomics/:id(.:format)      webcomics#update
                 DELETE /webcomics/:id(.:format)      webcomics#destroy
            root        /                             webcomics#index

路由正常;把match放在resources上面

也就是说,我会考虑将这些路由添加为RESTful操作:

resources :webcomics
  collection do
    get 'first'
    get 'random'
    get 'latest'
  end
end

在我看来,这有点干净,而且恰好相当适合。


这个问题是因为你在show模板中的编辑链接。编辑链接需要一个对象来编辑:

<%= link_to "edit", edit_webcomic_path(@webcomic) %>

把这三条match规则放在resources行上面,像这样:

match '/webcomics/first' => 'webcomics#first', :as => :first
match '/webcomics/random' => 'webcomics#random', :as => :random
match '/webcomics/latest' => 'webcomics#latest', :as => :latest
resources :webcomics

原因见Ruby指南:Routing:

Rails路由按照指定的顺序匹配,所以如果您有一个资源:照片上面有一个获取"照片/投票"的显示动作吗资源行路由将在get行之前匹配。来解决这个问题,将获取行移动到资源行上方,以便它是匹配第一。

相关内容

最新更新