1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで日本語をurlに使いたい時の書き方備忘録

1
Posted at

この記事で書くこと

  • /animals/隣の猫さん /animals/山奥の熊さん
    のようなurlを実現させるために何をする必要があるのか。

何も対処しないと、以下のようなanimals#showにリクエストすると URI::InvalidURIError が発生してしまう。 :disappointed:

animals_controller.rb
class AnimalsController < ApplicationController
  def show
    @animal = Animal.find_by(name: params[:name])
  end
end

結論

Controller

以下のようにutf-8にエンコードしてあげれば良い.

animals_controller.rb
class AnimalsController < ApplicationController
  before_action :encode_with_utf_8, only: :show

  def show
    @animal = Animal.find_by(name: params[:name])
  end

  private

  def encode_with_utf_8
    request.url.force_encoding("utf-8")
  end
end

テストはどう書くか

Ruby 2.7.0 リファレンスマニュアル | URI.encode_www_form_component を使用する。

spec/requests/animals_spec.rb
RSpec.describe 'Animals', type: :request do
  let(:animal) { create(:animal, name: '隣町の鳥さん') }

  describe 'GET /animals/:name' do
    context 'when animal exist' do
      it 'successes.' do
        url_encoded = URI.encode_www_form_component animal.name
        get "/animals/#{url_encoded}"
        expect(response).to be_success
      end
    end
  end
end
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?