未定义方法“update”用于空值:NilClass post scaffold

3

我试图更新一篇文章,在添加Redcarpet宝石后,当我尝试更新一个帖子时会出现错误。

这是错误信息:undefined method 'update' for nil:NilClass

这是我的文章控制器:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
      @post = Post.find_by_urlid(params[:urlid])
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edite
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)
      @post.urlid = SecureRandom.urlsafe_base64

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Your Post was successfully created!' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Your Post was successfully updated!' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'You have successfully deleted the Post!' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
        @post = Post.find_by_urlid(params[:urlid])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
        params.require(:post).permit(:urlid, :author, :title, :body, :likes, :dislikes, :tags)
    end
end

我查看了其他帖子,他们的答案都不起作用。有什么想法吗?
编辑:
服务器日志:
    Started PATCH "/posts/sfqm5y99cbomqh4nmuxq5w" for 127.0.0.1 at 2014-10-31 13:05:07 -0700
Processing by PostsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"FRRgB2pI6GAQa6YL8KLZrUShshjjGd7+IXrLv1hTi5E=", "post"=>{"author"=>"Un3qual", "title"=>"First post", "body"=>" on new *dev* system **:D**", "likes"=>"9999", "dislikes"=>"0", "tags"=>""}, "commit"=>"Update Post", "urlid"=>"sfqm5y99cbomqh4nmuxq5w"}
  Post Load (0.1ms)  SELECT  "posts".* FROM "posts"  WHERE "posts"."urlid" = 'sfqm5y99cbomqh4nmuxq5w' LIMIT 1
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `update' for nil:NilClass):
  app/controllers/posts_controller.rb:46:in `block in update'
  app/controllers/posts_controller.rb:45:in `update'


  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.4ms)
  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (0.6ms)
  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.6ms)
  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.9ms)


Started PATCH "/posts/sfqm5y99cbomqh4nmuxq5w" for 127.0.0.1 at 2014-10-31 15:42:18 -0700
Processing by PostsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"FRRgB2pI6GAQa6YL8KLZrUShshjjGd7+IXrLv1hTi5E=", "post"=>{"author"=>"Un3qual", "title"=>"First post", "body"=>" on new *dev* system **:D**", "likes"=>"9999", "dislikes"=>"0", "tags"=>""}, "commit"=>"Update Post", "urlid"=>"sfqm5y99cbomqh4nmuxq5w"}
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts"  WHERE "posts"."urlid" = 'sfqm5y99cbomqh4nmuxq5w' LIMIT 1
Completed 500 Internal Server Error in 4ms

NoMethodError (undefined method `update' for nil:NilClass):
  app/controllers/posts_controller.rb:46:in `block in update'
  app/controllers/posts_controller.rb:45:in `update'


  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.4ms)
  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (0.6ms)
  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.6ms)
  Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (10.2ms)

你能否在终端中使用 rails s 命令输出此请求的参数并发布服务器日志? - Surya
如果未找到记录,则会出现上述消息。您应该在before_action过滤器中设置条件,以便在未找到记录时重定向到另一个页面。'nil'对象没有activerecord方法。您可以确认在控制器中编写Post.find_by_urlid(sfqm5y99cbomqh4nmuxq5w)后是否输出了内容? - Ruby Racer
@RubyRacer 不对。我仍然得到 PostsController#update 中的 NoMethodError undefined method 'update' for nil:NilClass - Un3qual
抱歉,我的意思是在控制台中运行命令 Post.find_by_urlid(sfqm5y99cbomqh4nmuxq5w) - Ruby Racer
@RubyRacer 帖子加载(0.1毫秒)从“帖子”中选择“*”,其中“帖子”。“urlid”='sfqm5y99cbomqh4nmuxq5w'限制1 => nil - Un3qual
3个回答

2

1
根据你问题中的评论,这是由于该urlid没有记录导致的。
你应该像这样更改你的回调(before_action)过滤器。
def set_post
    @post = Post.find_by(urlid: params[:urlid])
    redirect_to posts_path, flash: {error: "The post does not exists"} if @post.nil?
end

这将重定向到帖子的索引页面,并显示错误消息(您应该在布局或模板中有一个用于出现的错误闪烁的div)。
如果@post存在,则会正常转发到操作。

你可以直接写成:error: "该文章不存在",不需要使用 flash: {error: "该文章不存在"} - Surya
@User089247,好的...我只是习惯这样使用。我认为它既不是错误的,也不是过时的。 - Ruby Racer

0
如果您没有使用任何实例化@post变量的预加载器,则会出现问题。对于update操作,您应该具有:
  def update
    @post = Post.find params[:id]
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Your Post was successfully updated!' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

现在我得到了:PostsController#update中的ActiveRecord::RecordNotFound 找不到没有ID的Post。 - Un3qual

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接