更新对象参数将 ID 附加到 URL 并抛出错误

Updating object parameters appends ID to URL & throws error

我的 rails 应用程序中有一个具有自定义 URL 路由的用户对象。当我提交更新表单时,出于某种原因,用户 ID 被附加到 URL,我收到了路由错误。

路线:

 get     'myaccount' => 'users#show', as: 'user'  
 get     'myaccount/edit' => 'users#edit'
 patch   'myaccount/edit' => 'users#update'
 put     'myaccount/edit' => 'users#update'

查看:

<%= form_for(@user) do |f| %>
  <%= render 'shared/error_messages', :form_object => @user %>

  <%= f.label :first_name %>
  <%= f.text_field :first_name, class: 'form-control' %>

  <%= f.label :last_name %>
  <%= f.text_field :last_name, class: 'form-control' %>


  <%= f.label :password %>
  <%= f.password_field :password, class: 'form-control' %>

  <%= f.label :password_confirmation %>
  <%= f.password_field :password_confirmation, class: 'form-control' %>

  <%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>

控制器动作:

  def update
    @user = User.find_by(id: current_user.id)
    if @user.update_attributes(user_params)
      # successful update
    else
      # unsuccessful update
    end
  end

错误: 提交后,URL 是 'myaccount.7',我收到错误消息: 路由错误 没有路由匹配 [PATCH] "/myaccount.7"

您有自定义路由,Rails 不清楚将表单发送到哪里以及使用哪种方法。您应该明确指定 urlmethod 选项。

 <%= form_for(@user, url: 'myaccount/edit', action: :put)  do |f| %>

Docs.

试试这个

resources :myaccount, controller: 'users'

输出:

  myaccount_index GET    /myaccount(.:format)                                                                users#index
                                         POST   /myaccount(.:format)                                                                users#create
                           new_myaccount GET    /myaccount/new(.:format)                                                            users#new
                          edit_myaccount GET    /myaccount/:id/edit(.:format)                                                       users#edit
                               myaccount GET    /myaccount/:id(.:format)                                                            users#show
                                         PATCH  /myaccount/:id(.:format)                                                            users#update
                                         PUT    /myaccount/:id(.:format)                                                            users#update
                                         DELETE /myaccount/:id(.:format)                                                            users#destroy
                                         GET    /myaccount(.:format)