この記事で書くこと
-
/animals/隣の猫さん/animals/山奥の熊さん
のようなurlを実現させるために何をする必要があるのか。
何も対処しないと、以下のようなanimals#showにリクエストすると URI::InvalidURIError が発生してしまう。 ![]()
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