RoR-未定义的方法“草稿?”对于nil:NilClass

时间:2018-10-10 17:53:48

标签: ruby-on-rails

实际上,我正在尝试在Rails 5博客应用程序中使用enum属性。问题是,当我尝试将状态从草稿状态切换到已发布状态,或反之亦然时,出现错误,提示“ BlogsController#toggle_status中的NoMethodError” < / p>

blogs_controller.rb

class BlogsController < InheritedResources::Base

  def toggle_status
    if @blog.draft?
       @blog.published!
    elsif @blog.published?
       @blog.draft!
    end

    redirect_to blogs_url, notice: "Blog status has been updated"
  end

  private

    def blog_params
      params.require(:blog).permit(:title, :body)
    end
end

index.html.slim

h1 Listing blogs

table
  thead
    tr
      th Title
      th Body
      th
      th
      th
      th

  tbody
    - @blogs.each do |blog|
      tr
        td = blog.title
        td = blog.body
        td = link_to blog.status,toggle_status_blog_path(blog)
        td = link_to 'Show', blog
        td = link_to 'Edit', edit_blog_path(blog)
        td = link_to 'Destroy', blog, data: { confirm: 'Are you sure?' }, method: :delete

br

= link_to 'New Blog', new_blog_path

blog.rb

class Blog < ApplicationRecord
  enum status: { draft: 0, published: 1 }
end

routes.rb

Rails.application.routes.draw do

  resources :blogs do 
    member do
      get :toggle_status
    end
  end
end

schema.rb

create_table "blogs", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "status", default: 0
  end

我不知道哪里可能出问题了,我尽了最大的努力,但无法弄清楚。

任何建议都是最欢迎的。

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要设置@blog实例变量。

def toggle_status
  @blog = Blog.find(params[:id])
  ...