Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

ruby - Confusion about passing instance variables to redirect_to method. As seen in Rails Guides

I am studying the ruby on rails guides namely, the "layouts and rendering" topic at http://guides.rubyonrails.org/layouts_and_rendering.html

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.

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:

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. But what in the world is going on with redirect_to(@book)? What exactly is that going to render and how is a book object going to be redirected to? BTW, the book model has columns, Name, author, pages etc...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

redirect_to documentation

redirect_to(options = {}, response_status = {}) Redirects the browser to the target specified in options. Record - The URL will be generated by calling url_for with the options, which will reference a named URL for that record.

So when one does redirect_to(@book) @book is a specific record with an id .

Thus, the associated records (in this case @book) show method is used as a template.

In addition to above, if you look at the routes.rb file which defines these paths you will notice

resources :books

Now this route is essentially translated as (you can see by running 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...