【问题标题】:Rails Routes not conforming to expected controller actionRails 路由不符合预期的控制器操作
【发布时间】:2014-08-05 15:17:47
【问题描述】:

我花了几个小时试图了解为什么我的 Rails 4 应用似乎不想路由到预期的控制器操作。

总而言之:我在浏览器 URL 中尝试的每一个操作似乎都进入了索引视图,即使我的路由看起来是正确的。我试图重新启动服务器等,希望可以解决它,但现在我完全迷失了。

例如,如果我尝试访问 localhost:3000/leads#new 上的 URL,我会收到以下错误消息:

Missing template leads/index, application/index with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in: * "/Users/me/Sites/azimuth/app/views"

如果我将 index.html.erb 的模板添加到 app/views/leads 文件夹,那么我不会收到错误消息 - 但是每条路径都会转到同一个索引视图 - 线索#show,线索#编辑等 - 所有这些。

这里是 routes.rb:

Azimuth::Application.routes.draw do

  # get 'leads', to: 'leads#new'

  resources :applicants
  resources :contacts
  resources :leads

  PagesController.action_methods.each do |action|
    get "/#{action}", to: "pages##{action}", as: "#{action}_page"
  end

  root "pages#home"
end

请注意,注释行 - get 'leads', to: 'leads#new' - 似乎是使路由正常工作的唯一方法。使用资源 :leads(我理解这是最佳实践?)让我很适应。

这是leads_controller.rb:

class LeadsController < ApplicationController
  def new
    @lead = Lead.new
  end

  def create
    @lead = Lead.new(lead_params)
    if @lead.save
        flash[:success] = "Thank you for reaching out! We'll be in touch soon."
        redirect_to 'home'
    else
        render 'new'
    end
  end

  def index
    @lead = Lead.all
  end

  private

    def lead_params
        params.require(:lead).permit(:first_name, :last_name, :subject, :message)
    end
end

Rake 路线 - 似乎一切正常。 (请注意,这只是显示与 Leads 对象相关的路线)。

        Prefix Verb   URI Pattern                    Controller#Action
         leads GET    /leads(.:format)               leads#index
               POST   /leads(.:format)               leads#create
      new_lead GET    /leads/new(.:format)           leads#new
     edit_lead GET    /leads/:id/edit(.:format)      leads#edit
          lead GET    /leads/:id(.:format)           leads#show
               PATCH  /leads/:id(.:format)           leads#update
               PUT    /leads/:id(.:format)           leads#update
               DELETE /leads/:id(.:format)           leads#destroy

我很困惑,似乎无法追踪发生了什么,希望能提供任何帮助!

【问题讨论】:

    标签: ruby-on-rails-4 routing routes rails-routing


    【解决方案1】:

    如果您错了,请纠正我,但我认为您正在尝试访问错误的 URL。您说您正在浏览器中访问localhost:3000/leads#new。该路由的正确 URL 是 localhost:3000/leads/new

    您何时在 config/routes.rb 文件中定义路由时,# 用于让 rails 知道您正在指定您的控制器之一的方法应响应此 URL。实际的 URL 不包含 #(通常来说)。

    【讨论】:

    • 没问题。我完全明白了!我在学习 Rails 时遇到了许多类似的问题。
    最近更新 更多