【问题标题】:Can't modify frozen hash无法修改冻结的哈希
【发布时间】:2013-06-24 03:05:34
【问题描述】:

每次尝试在下面运行此代码时,我都会不断收到上述错误。我正在尝试从表单中删除信息。可以看看“销毁”的方法吗?

class ArticlesController < ApplicationController

  def show
    @article = Article.find(params[:id])
  end

  def new   
    @article = Article.new
  end

  def create
    @article = Article.new(params[:article])
    @article.save
    redirect_to article_path(@article)
  end

  def destroy 
    @article = Article.new(params[:article])
    @article.delete
    @article.save
    redirect_to article_path(@article)   
  end

  def edit
    @article = Article.find(params[:id]) 
  end   
end

【问题讨论】:

  • @article 为什么删除后还要保存?

标签: ruby-on-rails ruby-on-rails-3 hash


【解决方案1】:

模型被删除或销毁后,您将无法更新或保存它。只需删除 @article.save 行。

另外,在你的destroy方法中,你为什么要创建一个Article的新实例只是在下一行删除它?你的destroy方法应该只有这个

def destroy
  @article.delete
  redirect_to article_path(@article)
end

你也可以在模型中定义destroy方法而不是控制器,然后简单地说

def destroy
  self.delete
end

【讨论】:

    【解决方案2】:

    我遇到了无法修改冻结的哈希问题,这是我用来修复它的解决方法/hack。这是一种解决方法,不是最终解决方案。

    放下桌子: - 从 Rails 控制台:ActiveRecord::Migration.drop_table(:table_name)

    模型文件编号加1,重命名文件: - db/migrate/1234_create_table_name.rb -> 1235_create_table_name.rb

    rake db:迁移

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 2022-10-23
      • 2021-02-19
      • 1970-01-01
      • 2015-11-18
      相关资源
      最近更新 更多