【问题标题】:Rails 3 'new' action as the index page due to a form由于表单,Rails 3“新”操作作为索引页面
【发布时间】:2012-01-14 14:53:52
【问题描述】:

我有一个小应用程序,其中的索引页面是指示用户发送电子邮件的表单,我更改了路线,以便 root_path 是呈现我的表单的“新”操作:

Oa::Application.routes.draw do
  resources :signups
  match "/confirm", :to => "pages#confirm"
  root :to => 'signups#new'
end

这工作正常,当我提交表单时它工作正常。当我在根页面上提交并导致验证错误时,地址栏有 url localhost:3000/signups 并显示我的验证错误,这也很好,但如果我要手动访问 http://localhost:3000/signups 它会给我一个错误“找不到 SignupsController 的操作‘索引’”。如果我创建了 'index' 操作和 redirect_to root_path 以便在我直接访问 http://localhost:3000/signups 时不会收到“找不到 SignupsController 的操作 'index'”,是否可以?这是正确的方法吗?

class SignupsController < ApplicationController
  def index
    redirect_to root_path
  end

  def new
    @signup = Signup.new
  end

  def create
@signup = Signup.new(params[:signup])
if @signup.save
      UserMailer.registration_confirmation(@signup).deliver
  flash[:notice] = "Signup created successfully."
  redirect_to confirm_path
else
  render :action => "new"
    end
  end
end

谢谢!

J

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    做这样的事情:

    post '/' => 'signups#create'
    root to: 'signups#new'
    

    不要使用resources :signups

    【讨论】:

    • Delba,这给了我一个错误没有路由匹配 [GET] "/"。另外,我为什么不使用资源?我计划稍后在此处添加其他操作。
    • 你确定吗?或root :to =&gt; 'signups#new'。我将更新我的答案,说明为什么在这种情况下不应该使用资源
    • 啊,是的,它确实有效,root :to => 'signups#new' 我也打错了。那么为什么我不应该使用资源呢?
    • 我无法解释清楚(英语不是我的母语)。简而言之:当发生验证错误时,url 是 create 操作的 url(在本例中为:POST '/signups')。看到无法通过 get 访问的 url 感觉不“自然”。所以当你不需要完整的资源时,选择POST 到一个已知的url。明白了吗?我怀疑..;-)
    • 一点澄清:我绝对不是说你应该永远使用resources。在您的特定情况下,如果您想要漂亮的路线,如果您只需要#new 和#create,请不要使用它。
    【解决方案2】:

    http://localhost:3000/signups 给我一个错误“找不到 SignupsController 的操作 'index'”的原因是:

    使用第一个“匹配”的路线。
    所以这一切:

    match "/confirm", :to => "pages#confirm"
    root :to => 'signups#new'
    

    被 /signups URL 忽略,因为它由

    处理

    资源:注册

    创建所有路由 - 索引、显示、创建、新建、编辑、更新、销毁

    当使用“注册”时,它意味着注册索引操作。

    尝试删除它和/或阅读 rails 中的 RESTful routes 并应用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多