-1

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

  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/first,但它给了我错误

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
4

2 回答 2

3

路由是有序的;把matches 放在resources.

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

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

IMO 这有点干净,并且恰好适合。


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

<%= link_to "edit", edit_webcomic_path(@webcomic) %>
于 2013-04-09T23:32:54.663 回答
3

将这三个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 Guides: Routing中有解释:

Rails 路由按照指定的顺序进行匹配,因此如果您在 get 'photos/poll' 上方有一个资源 :photos,则资源行的 show action 路由将在 get 行之前匹配。要解决此问题,请将 get 行移到资源行上方,以便首先匹配。

于 2013-04-09T23:28:46.743 回答