【问题标题】:undefined local variable or method `discussion' for #<DiscussionsController:0x598de20>#<DiscussionsController:0x598de20> 的未定义局部变量或方法“讨论”
【发布时间】:2013-05-09 09:30:45
【问题描述】:

这是我收到的错误消息

NameError in DiscussionsController#destroy

undefined local variable or method `discussion' for #<DiscussionsController:0x598de20>

我创建了一个 DiscussionsController

class DiscussionsController < ApplicationController
  def destroy
    @discussion = discussion.find(params[:id])

    if @discussion.present?
      @discussion.destroy
    end

    redirect_to root_path
  end
end

我正在尝试允许用户删除他们自己的讨论。 这是我用来允许删除的视图:

<% if current_user?(discussion.user) %>
  <%= link_to "delete", discussion, method: :delete,
                                    confirm: "You sure?",
                                    title: discussion.content %>
<% end %>

当我尝试时,它会转到 http://localhost:3000/disc/7 (7 = discussion_id) 并显示该错误。

我的routes.db的一部分

resources :discussions, :path => "disc"

我该如何解决这个问题?顺便问一下, DiscussionsController 是必需的吗?我创建它只是为了定义破坏。

以下 cmets 中错误的 Postcmets 表

 create_table "postcomments", :force => true do |t|
    t.text      "content"
    t.integer   "user_id"
    t.integer   "micropost_id"
    t.timestamp "created_at",      :null => false
    t.timestamp "updated_at",      :null => false
    t.text      "comment_content"
  end

Postcmets 模型

class Postcomment < ActiveRecord::Base


  attr_accessible :comment_content

  belongs_to :user
  belongs_to :micropost

  validates :comment_content, presence: true
  validates :user_id, presence: true
  validates :micropost_id, presence: true  

  default_scope order: 'postcomments.created_at ASC'
end

【问题讨论】:

  • 显然您的postcomments 表没有discussion_id 列。但正如我所说,请再问一个问题,因为这个新问题与原来的无关。

标签: ruby-on-rails ruby


【解决方案1】:

discussion 应该是大写的 D。而不是:

@discussion = discussion.find(params[:id])

尝试:

@discussion = Discussion.find(params[:id])

这是一个你试图调用方法的类,在 Ruby 中类总是以大写字母开头。

【讨论】:

  • 你知道为什么我尝试删除时会出现这个错误吗?我没有与讨论相关的 postcmets,所以我想知道我需要在哪里解决这个问题? SQLite3::SQLException: no such column: postcomments.discussion_id: SELECT "postcomments".* FROM "postcomments" WHERE "postcomments"."discussion_id" = 7 ORDER BY postcomments.created_at ASC
  • 这似乎与您之前的问题完全无关。所以,不,不知道。当您重定向到root_path 时,可能会发生这种情况。请提出另一个问题并发布相关代码。
猜你喜欢
  • 2017-01-26
  • 2018-04-19
  • 2015-01-01
  • 2013-12-17
  • 2016-04-29
  • 2018-04-21
相关资源
最近更新 更多