UsersController中的ActiveRecord :: RecordNotFound#deactivate(找不到'id'=的用户)

时间:2015-08-11 04:21:06

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

使用我的rails应用程序,我可以成功销毁,注册和登录用户,但我似乎可以停用它们。我每次都会收到此错误: ActiveRecord::RecordNotFound in UsersController#deactivate (Couldn't find User with 'id'=)

record = s.execute([id], self, connection).first
    unless record
      raise RecordNotFound, "Couldn't find #{name} with '#{primary_key}'=#{id}"
    end
    record
  rescue RangeError

这是用户控制器:

def deactivate
 user = User.find(params[:user_id])
  if current_user.admin?
  user.deactivate_account!
  redirect_to users_path 
  else
   redirect_to :back
 end
end

_user.html.erb视图:

<li><%= gravatar_for user, size: 50 %>
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
<%= link_to "delete", user, method: :delete,
                              data: { confirm: "You sure?" } %>
<% end %>

<% if current_user.admin? && @user != current_user %>
<%=link_to "deactivate", deactivate_path(user_id: @user), method: :post, 
                                         data: { confirm: "Are you sure?"}%> 
<% end %>
</li>

和路线:

get 'password_resets/new'
get 'password_resets/edit'
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
resources :account_activations, only: [:edit]
resources :password_resets,     only: [:new, :create, :edit, :update]
post '/deactivate', to: "users#deactivate"

日志是:

Rendered .../.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_source.erb (9.0ms)
Rendered .../.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_trace.html.erb (3.9ms)
Rendered .../.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_request_and_response.html.erb (1.5ms)
Rendered .../.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_web_console.html.erb (1.3ms)
Rendered .../.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/diagnostics.html.erb within rescues/layout (44.8ms)

可能有什么不对?我假设错误在控制器中。我正在关注Michael Hartl教程,因为我是初学者,但我也试图自己实现(就像这个)。

1 个答案:

答案 0 :(得分:2)

首先,您应该将此PUT请求改为POST,因为它正在更新用户记录。

以下是我为完成这项工作所做的更改:

修改了PUT文件中routes.rb的路线:

put 'deactivate/:id(.:format)', :to => 'users#deactivate', :as => :deactivate_user

您没有针对User模型的deactivate_account方法的实现。我做到了在您的用户模型中:

def deactivate_account
 update_attributes!(activated: false)
end

最后,像这样改变了用户的部分:

<%=link_to "Deactivate", deactivate_user_path(user), method: :put%>