如何链接到Ruby on Rails中的另一个.html.erb文件

时间:2017-07-22 20:17:42

标签: ruby-on-rails

我正在使用我的Rails项目,我收到此错误:

  

LeaguesController中的ActiveRecord :: RecordNotFound#show无法找到   联盟' id' =约

这是我的link_to

<%= link_to 'About', about_path %>

我的控制器:

class LeaguesController < ApplicationController
  before_action :set_league, only: [:show, :edit, :update, :destroy]

  # GET /leagues
  # GET /leagues.json
  def index
    @leagues = League.all
  end

  def about
  end

  # GET /leagues/1
  # GET /leagues/1.json
  def show
  end

  # GET /leagues/new
  def new
    @league = League.new
  end
end

我的routes.rb

Rails.application.routes.draw do
    resources :leagues
    get '/leagues/about' => 'leagues#about', as: => :about
end

请帮助我,我想将index.html.erbmy about.html.erb相关联。

2 个答案:

答案 0 :(得分:1)

在导轨routing guide中涵盖了这种情况:

  

Rails路由按照指定的顺序进行匹配,因此如果您有资源:获取'photos / poll'之上的照片,资源行的show action路线将在获取行之前匹配。要解决此问题,请将获取行移到资源行上方,使其首先匹配

取代:photos而不是:leagues而不是/poll,您拥有/about。因此,只需要在路由文件中交换这两行

Rails.application.routes.draw do
    get '/leagues/about' => 'leagues#about', as: :about
    resources :leagues
end

对于这种情况,您也可以

resources :leagues do
  get 'about', on: :collection
end

并以

结束
Prefix        Verb    URI Pattern                 Controller#Action
about_leagues GET    /leagues/about(.:format)    leagues#about

并最终以about_leagues_path作为帮助者(可能比about_path更好,关于什么?如果您之后有/teams/about,那么该怎么办?{{1关于球队或联赛?)

答案 1 :(得分:1)

leagues GET /leagues(.:format) leagues#index POST /leagues(.:format) leagues#create new_league GET /leagues/new(.:format) leagues#new edit_league GET /leagues/:id/edit(.:format) leagues#edit league GET /leagues/:id(.:format) leagues#show PATCH /leagues/:id(.:format) leagues#update PUT /leagues/:id(.:format) leagues#update DELETE /leagues/:id(.:format) leagues#destroy 生成路线

leagues#show

然后,您要添加的自定义路由与为/leagues/:id操作委派的路由具有相同的网址蓝图(即:id ),rails路由器假定match为&#39; about&#39;。您可以使用match '/leagues/about' => 'leagues#about', as: :about, via: :get 来解决此问题:

'