简体   繁体   中英

Can't modify frozen hash

I keep getting the above error everytime i try to run this code below. I am trying to delete information from a form. can you look at the "destroy" method?

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

You cannot update or save a model after it has been deleted or destroyed. Just remove the @article.save line.

Also, in your destroy method, why would you create a new instance of Article only to delete it on the next line? Your destroy method should have only this

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

You could also define the destroy method in the model instead of the controller and simply say

def destroy
  self.delete
end

I experienced the can't modify frozen hash issue and this is the workaround/hack I used to fix it. This is a workaround not final solution.

Drop the table: - From rails console: ActiveRecord::Migration.drop_table(:table_name)

Increment the model file number by 1, rename the file: - db/migrate/1234_create_table_name.rb -> 1235_create_table_name.rb

rake db:migrate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM