ruby-on-rails - Ruby on Rails 未定义方法 `destroy' for nil:NilClass
问题描述
我在删除用户帖子时遇到问题:
nil:NilClass 的未定义方法“destroy”
# routes.rb
Rails.application.routes.draw do
get 'sessions/new'
get 'users/new'
get 'user/new'
root to:'pages#home'
get '/home', to:'pages#home'
get '/help', to:'pages#help'
get '/about', to:'pages#about'
get '/contact', to:'pages#contact'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
post '/micro_posts', to: 'microposts#create'
delete '/micro_posts', to: 'microposts#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :microposts, only: [:create, :destroy]
end
# microposts_controller.rb
class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: [:destroy]
def create
@micropost = current_user.micro_posts.build(req_params)
if @micropost.save
flash[:success] = "Post created"
redirect_to root_url
else
@feed_items = []
render 'pages/home'
end
end
def destroy
@micropost.destroy
flash[:success] = "Post deleted"
redirect_to request.referrer || root_url
end
private
def req_params
params.require(:micro_post).permit(:content)
end
def correct_user
@micropost = current_user.micro_posts.find_by_id(params[:id])
redirect_to root_url if @micropost.nil?
end
end
# _micro_post.html.erb file
<li id="micropost" ><%= micro_post.id %>
<%= link_to gravatar_for(micro_post.user, size: 50), micro_post.user %>
<span class="user" ><%= link_to micro_post.user.name, micro_post.user %></span><br/>
<span class="content" ><%= micro_post.content %></span>
<br/>
<span class="timestamp">
posted <%= time_ago_in_words(micro_post.created_at) %> ago
<% if current_user?(micro_post.user) %>
<%= link_to ' | Delete', micro_posts_path, method: :delete , data: { confirm: "Are you sure" } %>
<% end %>
</span>
<br/>
</li>
现在我发现我的错误出现在引用方法“correct_user”中的 microposts_controller.rb 文件中,因为它找不到 micropost 的 id 并返回 nil。所以我们不能在 nil 对象上调用 destroy 方法。你能告诉我为什么它没有找到微博ID吗?
Started DELETE "/micro_posts" for 127.0.0.1 at 2019-02-21 21:43:17 +0500
(0.7ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
↳ C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
Processing by MicropostsController#destroy as HTML
Parameters: {"authenticity_token"=>"aNeBnIy/JOrWz+sQdzU2w06faILW2dM+f8SPwmXVmJs1XfJ8OqbkgPVwkpoY/HBjh8YJhVPWZ4BC1Onxg0AtWw=="}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/helpers/sessions_helper.rb:16
MicroPost Load (0.3ms) SELECT "micro_posts".* FROM "micro_posts" WHERE "micro_posts"."id" IS NULL LIMIT ? [["LIMIT", 1]]
↳ app/controllers/microposts_controller.rb:36
Completed 500 Internal Server Error in 56ms (ActiveRecord: 1.9ms)
NoMethodError (undefined method `destroy' for nil:NilClass):
app/controllers/microposts_controller.rb:22:in `destroy
解决方案
如果您不介意,我会将我的评论转换为答案,以免留下未回答的问题。
你有一个命名问题。模型是MicroPost
,但控制器是MicropostsController
。这就是您尝试创建自定义路线的原因。
您需要将控制器重命名为MicroPostsController
并将其文件重命名为micro_posts_controller.rb
. 从 routes.rb 中删除这两行:
post '/micro_posts', to: 'microposts#create'
delete '/micro_posts', to: 'microposts#destroy'
并在此处更改microposts
为micro_posts
(注意下划线):
resources :microposts, only: [:create, :destroy]
用于micro_post_path(micro_post)
删除视图中的链接
推荐阅读
- kendo-ui - 如何在两个形状之间动态建立连接,意味着位置和所有将在剑道图中动态传递
- javascript - 本地存储不适用于记住类切换的最后用户输入
- python - 无法将 feed_dict 键解释为 Tensor:Tensor Tensor("Placeholder:0", shape=(135162, 6), dtype=float32) is not an element of this graph
- typescript - 运行一个将 typescript 测试与 jest 合并的声明
- javascript - 对检测功能存在的“hasOwnProperty”感到困惑
- c# - 如何在 html 中将字符串转换为 html
- php - 如何在保留兄弟键值对的同时基于键值与数组相交
- python - 检查一个数组中的元素是否存在于另一个数组中?
- python - 如何从第二项迭代python dict
- java - 通过实现 onSeekBarChangeListener 在 TextView 中的多个搜索栏值