5

Rails で 2 番目のプロジェクトをセットアップし (最初はチュートリアルに従わなかった)、ルートで解決できない問題に遭遇しました。次のように、routes.rbファイルを使用して、すべてが希望どおりに機能します。

AnimalApp::Application.routes.draw do

    root to: 'static_pages#index'
        # resources :animal
    match '/help', to: 'static_pages#help'
    match '/about', to: 'static_pages#about'
    match '/contact', to: 'static_pages#contact'
    match '/league', to: 'static_pages#league'
    match '/animal', to: 'animal#new'

私が私の動物にアクセスできないことを除いて!/animal/1 に移動するとエラーがスローされます: No route matches [GET] "/animal/1"

これを修正するために、ルートを次のように変更しました。

    AnimalApp::Application.routes.draw do

    root to: 'static_pages#index'
        resources :animal
    match '/help', to: 'static_pages#help'
    match '/about', to: 'static_pages#about'
    match '/contact', to: 'static_pages#contact'
    match '/league', to: 'static_pages#league'
    #match '/animal', to: 'animal#new'

ただし、サイトの他のページを表示しようとすると、次のエラーが表示されます。 No route matches {:action=>"show", :controller=>"animal"}

詳細については、以下のコントローラーを参照してください: (静的ページ)

class StaticPagesController < ApplicationController
  def help
  end

  def league
  end

  def contact
  end

  def about
  end

  def index
  end

  def show
  end
end

動物コントローラー

class AnimalController < ApplicationController
    def new
    @animal = Animal.new
    end

def show
    @animal = Animal.new
end
end

また、実行した結果は次のrake routesとおりです。

animal_index GET    /animal(.:format)          animal#index
            POST    /animal(.:format)          animal#create
  new_animal GET    /animal/new(.:format)      animal#new
 edit_animal GET    /animal/:id/edit(.:format) animal#edit
      animal GET    /animal/:id(.:format)      animal#show
             PUT    /animal/:id(.:format)      animal#update
          DELETE    /animal/:id(.:format)      animal#destroy
            root    /                          static_pages#index
            help    /help(.:format)            static_pages#help
           about    /about(.:format)           static_pages#about
         contact    /contact(.:format)         static_pages#contact
          league    /league(.:format)          static_pages#league
                    /animal(.:format)          animal#new

サイトを元に戻し、URI /animal/[:id] の下で動物データベースのオブジェクトを表示できるようにする方法を知っている人はいますか?

4

1 に答える 1

5

resources :animals代わりに作るresources :animal

rake routes次の出力が表示されます。

    animals GET    /animals(.:format)          animals#index
            POST   /animals(.:format)          animals#create
 new_animal GET    /animals/new(.:format)      animals#new
edit_animal GET    /animals/:id/edit(.:format) animals#edit
     animal GET    /animals/:id(.:format)      animals#show
            PUT    /animals/:id(.:format)      animals#update
            DELETE /animals/:id(.:format)      animals#destroy
于 2012-10-20T17:12:05.003 に答える