我对Ruby on Rails很陌生,我正在努力学习,所以我尝试了一个新功能。
我现在得到的错误是:
ActionController::RoutingError (No route matches [POST] "/users/2"):
我正在尝试创建一个功能来将其他用户提升为管理员,这只能作为管理员使用。 我的 users_controller.rb 包含:
def promote
if !User.find(params[:id]).admin?
User.find(params[:id]).toggle!(:admin)
flash[:success] = "User is promoted to admin."
redirect_to users_url
else
flash[:danger] = "Admins can't demote other admins."
redirect_to users_url
end
end
我的 _user.html.erb 包含:
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
<% if !user.admin? %>
<br /> <%= link_to "Delete User", user, method: :delete,
data: { confirm: "You sure?" } %>
| <%= link_to "Promote to Admin", user, method: :promote,
data: { confirm: "You sure?" } %>
<% end %>
<% end %>
然后我们有 routes.rb ,其中包含:
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
get 'users/new'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users do
member do
get :following, :followers
end
end
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
end
我无法确切地发现出了什么问题。一些建议会很棒!
答案 0 :(得分:0)
def promote
@user = User.find(params[:id])
if @user.admin?
@user.toggle!(:admin)
flash[:success] = "User is promoted to admin."
redirect_to users_path
else
flash[:notice] = "Admins can't demote other admins."
redirect_to users_path
end
end
<%= link_to @user.name, @user %>
<% if current_user.admin? && !current_user?(@user) %>
<% if !@user.admin? %>
<br />
<%= link_to "Delete User", @user, method: :delete, data: { confirm: "You sure?" } %>
| <%= link_to "Promote to Admin", promote_users_path(user), method: :put, data: { confirm: "You sure?" } %>
<% end %>
<% end %>
路线
resources :users do
member do
get :following, :followers,
put :promote
end
end
或
match '/users', to: 'users#promote', via: :put