redirect_toになんでインスタンス変数??
Hey guys!!:)
今日もstackoverflowの記事を訳すよー。今回は2013年に投稿した古い記事だけど、初心者の勉強の為には良記事だなと思ってピックアップした。
–質問–
I am confused about passing an instance variable to a redirect_to method. How is this possible? I thought redirect_to would be relevant for redirecting to another webpage or a url.
redirect_toメソッドにインスタンス変数を受け渡していることについて混乱している。なんでこんなことが出来るの?私はredirect_toは他のウェブページやURLを表示させることと関係するのだと思ってたよ。
In the examples given on the guide it says the following:
あるガイドが下記のような例でこんなこと説明していたんだ;
2.2.2 Rendering an Action’s View If you want to render the view that corresponds to a different action within the same template, you can use render with the name of the view: もし同じテンプレートで違うアクションを実行させたかったら、renderにviewの名前を渡して使えるよ。 def update @book = Book.find(params[:id]) if @book.update_attributes(params[:book]) redirect_to(@book) else render "edit" end end
The render “edit” makes complete sense, its going to render that new form again.
render editは確かに理に適っていて、新しいフォームを再度表示させる。
But what in the world is going on with redirect_to(@book)?
でもredirect_to(@book)って一体何なんだ?
What exactly is that going to render and how is a book object going to be redirected to?
具体的にrenderは何をして、bookオブジェクトはどのようにしてリダイレクトしているんだ?
BTW, the book model has columns, Name, author, pages etc…
追記すると、bookモデルはカラム、名前、作者、ページ等がある。
–回答–
redirect_to(options = {}, response_status = {}) Redirects the browser to the target specified in options. redirect_to(options = {}, response_status = {})ブラウザをオプションで指定した所にリダイレクトする。 Record - The URL will be generated by calling url_for with the options, which will reference a named URL for that record. レコード - URLはオプションでurl_forを呼びだすことによって生成される。そのレコードより名付けられたURLを参照する。
So when one does redirect_to(@book)
@book
is a specific record with an id .
なのでredirect_to(@book)
を実行した時、@book
はidのもつ特定のレコードだ。
Thus, the associated records (in this case @book) show method is used as a template.
したがって、関連のレコード(このケースでは@book)があるshowメソッドはテンプレートに使われる。
In addition to above, if you look at the routes.rb
file which defines these paths you will notice
上記に加えてもしroutes.rb
ファイルをみてみたら、下記のようなパスが定義されていて何か気づくだろう。
resources :books
Now this route is essentially translated as (you can see by running rake routes)
このルートは下記のように読み込まれる(rake routesを実行すればみれるよ)。
books GET /books(.:format) books#index POST /books(.:format) books#create new_book GET /books/new(.:format) books#new edit_book GET /books/:id/edit(.:format) books#edit book GET /books/:id(.:format) books#show PUT /books/:id(.:format) books#update DELETE /books/:id(.:format) books#destroy
Notice the book GET /books/:id books#show
- which gets matched when you do redirect_to(@book)
book GET/books/:id books#show
で何か気づくかな?これはredirect_to(@book)と結びついているんだ。
終わり
どうだったかな?たしかにインスタンス変数を引数にしているのには違和感があった。
この記事を読んで少し霧が晴れたような気がしたかな!
see you!!
リンク