ActiveRecord :: RecordNotFound“无法找到id = new的用户”

时间:2013-12-12 21:36:49

标签: ruby-on-rails activerecord

每当我点击表单中的更新按钮时,它都会重定向到/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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

你想要使用它:

redirect_to user_path(@user)

以下是关于主题的rails参考:http://api.rubyonrails.org/classes/ActionController/Redirecting.html