【问题标题】:Rails NoMethodError 'each' when trying to destroy recordRails NoMethodError 'each' 尝试销毁记录时
【发布时间】:2018-02-03 09:58:24
【问题描述】:

我有一个带有一些表(答案、问题、项目)的 rails 应用程序,答案通过外键链接到问题,我的问题控制器中的销毁方法定义如下:

def destroy
        @pregunta = Question.find(params[:id])
        @pregunta.destroy
        flash[:danger] = "Se ha borrado la pregunta"
        redirect_to questions_path
    end 

我的 ANSWER 模型有以下限制:

belongs_to :question, :dependent => :destroy
    has_many :answers_projects, :dependent => :destroy
    has_many :projects, through: :answers_projects, :dependent => :destroy

但是当我尝试像这样调用我的销毁方法时(在我看来):

<% @preguntas.each do |pregunta| %>
    <tr>
      <td><%= pregunta.question %></td>
      <td><%= pregunta.get_process_name %></td>
      <td><%= pregunta.input %></td>
      <td><%= pregunta.count_op %></td>
      <td><%= pregunta.area %></td>
      <td><%= link_to 'Mostrar', question_path(pregunta), class: "btn btn-xs btn-info" %></td>
      <td><%= link_to 'Editar', edit_question_path(pregunta) , class: "btn btn-xs btn-warning"%></td>
      <td><%= link_to 'DELETE',question_path(pregunta),method: :delete, data: {confirm: '¿Estás seguro de que deseas eliminar la pregunta? Esta acción no se puede deshacer'}, class: "btn btn-xs btn-danger"%></td>

我可以在我的开发环境中销毁记录,但在我的部署环境中,我的 Heroku 日志中出现以下错误:

AnswersProject Load (0.7ms)  SELECT "answers_projects".* FROM "answers_projects" WHERE "answers_projects"."answer_id" = $1  [["answer_id", 95]]
2018-02-02T23:14:19.329550+00:00 app[web.1]: [bb557967-7424-414b-9684-b31ad439936a]    (0.6ms)  ROLLBACK
2018-02-02T23:14:19.337619+00:00 app[web.1]: [bb557967-7424-414b-9684-b31ad439936a] Completed 500 Internal Server Error in 140ms (ActiveRecord: 30.3ms)
2018-02-02T23:14:19.338990+00:00 app[web.1]: [bb557967-7424-414b-9684-b31ad439936a]   
2018-02-02T23:14:19.339160+00:00 app[web.1]: [bb557967-7424-414b-9684-b31ad439936a] NoMethodError (undefined method `each' for #<Answer:0x00000004d173e8>):
2018-02-02T23:14:19.339198+00:00 app[web.1]: [bb557967-7424-414b-9684-b31ad439936a]   
2018-02-02T23:14:19.339242+00:00 app[web.1]: [bb557967-7424-414b-9684-b31ad439936a] app/controllers/questions_controller.rb:77:in `destroy'

如您所见,我收到 NoMethodError(仅在部署应用程序后发生)可能是什么原因造成的,如何解决? 如果需要,我会从我的控制器和模型中发布更多代码,在此先感谢 :)

编辑 完整的问题控制器:

class QuestionsController < ApplicationController
    before_action :require_user
    before_action :require_project
    before_action :require_user, except: [:new, :create]
    before_action :current_project, only: [:index]
    def index
        @preguntas = Question.all.order(:process)
        @project_id = request.original_url.split('.').last
        set_current_project(@project_id)
    if(@project_id.include? "http")
    @project_id = "0"
    end
        if(@project_id != "0")
            @proyecto = Project.find(@project_id)
        end 
    end

def show
    @pregunta = Question.find(params[:id])
    @opciones = Option.where(question_id: @pregunta)
end

def new
puts "HELLO EVERYONE NEW QUESTION"
  @pregunta = Question.new
    for option in @pregunta.options
        option.question_id = 1
        option.build
    end
end

def create
puts "HELLO EVERYONE CREATE QUESTION"
    @pregunta = Question.new(pregunta_params)
    if @pregunta.save
    @counter = 0
    @step = 1.to_f / @pregunta.options.count
    for option in @pregunta.options
        @counter = @counter + 1
        if @counter == @pregunta.options.count
            option.update_value(1.to_f)
        else
            option.update_value(@step * @counter)
        end
    end
         redirect_to @pregunta
    else
         render 'new'
    end
end
    def edit
        @pregunta = Question.find(params[:id])
    end 

    def update
puts "HELLO EVERYONE UPDATE UPDATE"
      @pregunta = Question.find(params[:id])
      @pregunta.options.build
      if @pregunta.update(pregunta_params)
        @counter = 0
            @step = 1.to_f / @pregunta.options.count
            for option in @pregunta.options
                @counter = @counter + 1
                if @counter == @pregunta.options.count
                    option.update_value(1.to_f)
                else
                    option.update_value(@step * @counter)
                end
            end
        redirect_to @pregunta
      else
        render 'edit'
      end
    end


     def destroy
        @pregunta = Question.find(params[:id])
        Answer.where(:question_id => @pregunta.id).destroy_all
        @pregunta.destroy
        flash[:danger] = "Se ha borrado la pregunta"
        redirect_to questions_path
    end 

    def require_same_user 
        set_project
        if current_user != @project.user && !@current_user.admin?
            flash[:danger] = "Solo puedes editar tus artículos"
            redirect_to root_path
        end 
    end 

    def require_project
        if current_user.projects.count <1 && !current_user.admin?
            redirect_to root_path
        end 
    end 

    private
        def pregunta_params
            params.require(:question).permit(:question, :value, :process, :area, :input, options_attributes: Option.attribute_names.map(&:to_sym).push(:_destroy))
        end
end

编辑 完整问题模型:

class Question < ApplicationRecord  
    has_many :options, dependent: :destroy
    accepts_nested_attributes_for :options, allow_destroy: true, reject_if: proc { |att| att['description'].blank? }
    validates :question, presence: true
        validates :value, presence: true, length: { minimum: 1 }
        validates :area, presence: true, length: { minimum: 3 }

        def count_op
            Option.where("description IS NOT NULL").where(question_id: self.id).count
        end

        def get_op
            Option.where("description IS NOT NULL").where(question_id: self.id)
        end
        def get_process_name
            case self.process
                when 1 
                    "1 - Identificación de grupo"
                when 2
                    "2 - Reflexión de desarrollo comunitario"
                when 3 
                    "3 - Problemáticas comunitarias - priorización"
                when 4 
                    "4 - Plan de trabajo comunitario"
                when 5 
                    "5 - Desarrollo de actividades y proyectos"
                when 6 
                    "6 - Operación de proyectos y seguimiento a cumplimiento de metas"
                when 7 
                    "7 - Seguimiento a proyectos comunitarios"
                when 8 
                    "8 - Fortalecimiento - operación de grupo"
                when 9 
                    "9 - Capacitación metodológica para vinculación y desarrollo comunitario"
                when 10 
                    "10 - Creación de redes y alianzas comunitarias"
                when 11 
                    "11 - Realización de planes de desarrollo local"
                when 12
                    "12 - Seguimiento a proyectos"
                when 13
                    "13 - Fortalecimiento operación de grupo"
                when 14
                    "14 - Creación de redes y alianzas institucionales"
                else
                    "Error en la fase"
            end
        end
end

【问题讨论】:

  • 销毁记录后重定向到哪里?你的控制器是什么样子的?
  • 我重定向回 questions_path,我添加了完整的问题控制器
  • 显示问题模型,错误很可能源于那里。
  • 这有点奇怪,在您显示的代码中,您没有加载Answer 记录或调用任何答案关系。所以我怀疑heroku上的代码跟你本地的不是最新的,或者问题是我们这里没有看到的一些代码造成的。
  • QuestionsController 中的第 77 行是哪一行?

标签: ruby-on-rails ruby heroku nomethoderror


【解决方案1】:

我认为当你创建你的模型时,.answer_projects 是 nil,所以当它试图破坏 .projects 时,它找不到与 .answer_projects 关联的每个模型。尝试改变

has_many :answers_projects, :dependent => :destroy
has_many :projects, through: :answers_projects, :dependent => :destroy

has_many :answers_projects
has_many :projects, through: :answers_projects

【讨论】:

  • 如果没有 answers_projects,.answers_projects 不为零。这是一个空数组。
  • 我试过了,但我仍然收到一个错误,我的控制台显示:(PG::ForeignKeyViolation:错误:更新或删除表“问题”违反了表“答案”上的外键约束“fk_rails_3d5ed4418f”
  • 你能发布你的问题模型吗?至少是关系?
  • 删除问题时,是否要删除与该问题相关的所有答案?您可能需要将has_many :answers 添加到您的问题模型中
【解决方案2】:

你为什么回答belongs_to :question, :dependent => :destroy? 当你破坏一个答案时,你想破坏一个问题吗? 你对 has_many 的答案有疑问吗?

这可能是问题所在。

如果没有,我也发现了一些改进。您正在定义很多实例变量(@project_id、@counter、@step 等)。您是否需要在视图中访问这些变量?为什么不直接使用project_id、counter、step?

编辑

在 QuestionsController#destroy 中发布错误后:为什么不在 Question 模型中添加 question has_many :answersdependent destroy?这样你就不需要在销毁问题之前执行 destroy_all 了。

class Question < ApplicationRecord  
  has_many :options, dependent: :destroy
  has_many :answers, dependent: :destroy
  accepts_nested_attributes_for :options, allow_destroy: true, reject_if: proc { |att| att['description'].blank? }
  validates :question, presence: true
  validates :value, presence: true, length: { minimum: 1 }
  validates :area, presence: true, length: { minimum: 3 }

问题控制器

def destroy
  @pregunta = Question.find(params[:id])
  @pregunta.destroy
  flash[:danger] = "Se ha borrado la pregunta"
  redirect_to questions_path
end 

【讨论】:

  • 感谢您指出这一点!我删除了 Answer 模型中的依赖项,我需要它们根据现有选项的数量动态填充一些值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多