stringexを使用して、stackoverflow のように、より使いやすい URL を実装しました。次に、次のように URL を有効にします。
http://localhost:8000/questions/12/i-want-to-display-the-url-like-stackoverflow
もちろん、入力すると、さらにSOのステップが見つかりました
http://stackoverflow.com/questions/30683457
URLアドレスバーで、SOは対応する質問にリダイレクトします
http://stackoverflow.com/questions/30683457/why-i-got-the-error-couldnt-find-article-with-id-ni-hao-wo-zhen-de-henhaoma-w
、
しかし、私のアプリではfind_by_slug!()
、レコードを取得していたので、入力http://localhost:8000/questions/12
するとエラーがスローされます。
ActiveRecord::RecordNotFound in QuestionsController#show
Couldn't find Question with slug = 12
このような 2 種類の URL を同時に有効にするにはどうすればよいですか? ルート ルールを追加できるかどうか、追加できる場合はどうすればよいですか?
了解しました
特に、私の Rails アプリは、プラグインinherited-resourcesを含むsocial-stream engineに基づいており、デフォルトのメソッドを持っているため、次のようにオーバーライドします。inherited-resources
find_by_id()
find_by_slug()
更新しました
Rails Routingに関するいくつかのマニュアルを読んだ後、入力すると にリダイレクトされるhttp://ip:port/questions/:id
など、 を有効にしました。http://localhost:8000/questions/12
http://localhost:8000/questions/12/i-want-to-display-the-url-like-stackoverflow
routes.rb
match 'questions/:id' => redirect { |params, req|
id = params[:id]
slug = Question.find_by_id(params[:id].to_i).slug
'/questions/' + id + '/' + slug
}
これが正しい方法かどうかわかりませんか?