【问题标题】:Getting "No Route matches" error when though I have a method in my controller当我的控制器中有一个方法时出现“无路由匹配”错误
【发布时间】:2016-07-06 07:22:34
【问题描述】:

我使用的是 Rails 4.2.3。我的控制器文件中有这个,“./app/controllers/users_controller.rb”……

  def edit
    @user = User.find(session["user_id"])
    render 'edit'
  end

  def update
    @user = User.find(session["user_id"])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
    end
    render 'edit'
  end

我的“./app/views/users/edit.html.erb”文件中有这个

    <%= form_for(@user) do |f| %>
    …
        <%= button_to "Save", { :action => "update" }, :method => :post, :class => 'button' %>

但是当我访问我的网址“http://localhost:3000/users/edit”时,我收到了这个错误

No route matches {:action=>"update", :controller=>"users"}

这是我在 routes/config.rb 中的内容,所以我不确定它为什么会分崩离析……

  get "users/edit" => "users#edit"
  resources :users

【问题讨论】:

    标签: ruby-on-rails configuration routes


    【解决方案1】:

    我相信您需要使用 PUT/PATCH 方法进行更新操作,而根据 Rails documentation 使用 POST 进行创建操作:

        <%= button_to "Save", { :controller => "users", :id => @user.id }, :method => :put, :class => 'button' %>
    

    另外,rake routes 是一个非常有用的命令,用于调试转储所有已定义路由的路由问题。

    【讨论】:

    • 我将按钮代码更改为“ "update" }, :method => :put, :class=> 'button' %>"但是当我访问localhost:3000/users/edit 时,我仍然得到同样的错误。
    • @Dave 更新了答案 - 尝试传递 { :controller =&gt; "users", :id =&gt; @user.id }。不幸的是,无法测试,但这应该可以。
    • 还查看了您的代码——您可以使用f.submit 代替,即&lt;%= form_for(@user, :method =&gt; :put) do |f| %&gt; 然后f.submit 而不是button_to
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多