【问题标题】:ActiveRecord::RecordNotFound "Couldn't find user with id=new"ActiveRecord::RecordNotFound "找不到 id=new 的用户"
【发布时间】:2013-12-13 05:50:51
【问题描述】:

每当我单击表单中的更新按钮时,它都会重定向到/users/new.1,从而引发错误Couldn't find User with id=new。请帮忙!

user_controller.rb

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      redirect_to @user
    else
      render "edit"
    end
  end

  private
  def user_params
    params.require(:user).permit(:id, :name, :password, :password_confirmation, :email, :password_salt, :password_hash, :phone)
  end 

edit.html.erb

<%= form_for @user, url: user_path(@user), method: :patch do |f| %>
    <p>
        <%= f.label :name %><br />
        <%= f.text_field :name %><br />
        <%= f.label :mobile %><br />
        <%= f.text_field :phone %><br />
        <%= f.label :email %><br />
        <%= f.text_field :email  %><br />
        <%= f.label :role %><br />
        <%= f.text_field :role  %><br />
    <p class="button"><%= f.submit "Update"%></p>
<% end %>

routes.rb

  get "logout" => "pages#destroy", :as => "logout"
  get 'welcome/index'
  get 'users/new', :as => 'user'
  root :to => 'welcome#index'
  resources :users

【问题讨论】:

  • 能否请您查看您的 routes.rb 文件,尤其是您为用户定义资源的地方?
  • 是的,当然。我已经编辑了我的问题。
  • 您不应该需要 get 'users/new', :as =&gt; 'user' 行,因为 resources :users 处理该路线。这可能是你的问题。
  • 谢谢,它解决了我的问题。
  • 您需要在控制器编辑方法中为该字段设置默认值。

标签: ruby-on-rails activerecord


【解决方案1】:

从您的 routes.rb 文件中删除无关的 get 'users/new', :as =&gt; 'user' 行。 resources :users 为您处理所有 CRUD 路由。

【讨论】:

    【解决方案2】:

    对于 redirect_to 你必须给它路径(或控制器和动作)。

    你会想要使用这个:

    redirect_to user_path(@user)

    这是有关该主题的 Rails 参考:http://api.rubyonrails.org/classes/ActionController/Redirecting.html

    【讨论】:

    • 这不是必需的。如果你通过了实例,并且配置了正确的路由,Rails 会自动从资源中检测路径。
    • 这通常不是我使用redirect_to 的经验,我以前见过这个确切的问题,我相信这就是我解决它的方法。不过,我可能是错的。
    • 是的,我为您添加了一个新答案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    相关资源
    最近更新 更多