我的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
错误: 提交后,网址为“myaccount.7&#39;我收到错误: 路由错误 没有路线匹配[PATCH]&#34; /myaccount.7&#34;
答案 0 :(得分:1)
您有自定义路由,并且Rails在发送表单和使用哪种方法时感到困惑。您应该明确指定url
和method
选项。
<%= form_for(@user, url: 'myaccount/edit', action: :put) do |f| %>
答案 1 :(得分:0)
试试这个:
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)