incompatible character encodings: UTF-8 and ASCII-

2019-09-10 16:30发布

问题:

ActionView::Template::Error (incompatible character encodings: UTF-8 and ASCII-8BIT): app/controllers/posts_controller.rb:27:in `new'

  # GET /posts/new
  def new
    if params[:post]
      @post = Post.new(post_params).dup
      if @post.valid?
        render :action => "confirm"
      else
        format.html { render action: 'new' }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    else
      @post = Post.new
      @document = Document.new
      @documents = @post.documents.all
      @document = @post.documents.build
    end

I don't know why it is happening.

回答1:

  • Make sure config.encoding = "utf-8" is there in application.rb file.
  • Make sure you are using 'mysql2' gem instead mysql gem
  • Putting # encoding: utf-8 on top of rake file.
  • Above Rails.application.initialize! line in environment.rb file, add following two lines:

    Encoding.default_external = Encoding::UTF_8

    Encoding.default_internal = Encoding::UTF_8

solution from here: http://rorguide.blogspot.in/2011/06/incompatible-character-encodings-ascii.html

If above solution not helped then I think you either copy/pasted a part of your Haml template into the file, or you're working with a non-Unicode/non-UTF-8 friendly editor.

If you can recreate that file from the scratch in a UTF-8 friendly editor. There are plenty for any platform and see whether this fixes your problem.

Sometimes you may get this error:

incompatible character encodings: ASCII-8BIT and UTF-8

That typically happens because you are trying to concatenate two strings, and one contains characters that do not map to the character-set of the other string. There are characters in ISO-8859-1 that do not have equivalents in UTF-8, and vice-versa and how to handle string joining with those incompatibilities requires the programmer to step in.



回答2:

I was upgrading my rails and spree and the error was actually coming from cache

Deleting the cache solved the problem for me

rm -rf tmp/cache