How the redirect_to method works in ruby

Here is my update function, at the moment when something is updated, it is great for http://localhost:3000/articles/2

 def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

How does redirect_to @articleartiles / 2 / page work and show?

Below are my routes

       Prefix Verb   URI Pattern                  Controller#Action
     articles GET    /articles(.:format)          articles#index
              POST   /articles(.:format)          articles#create
  new_article GET    /articles/new(.:format)      articles#new
 edit_article GET    /articles/:id/edit(.:format) articles#edit
      article GET    /articles/:id(.:format)      articles#show
              PATCH  /articles/:id(.:format)      articles#update
              PUT    /articles/:id(.:format)      articles#update
              DELETE /articles/:id(.:format)      articles#destroy
welcome_index GET    /welcome/index(.:format)     welcome#index
         root GET    /                            welcome#index
+4
source share
4 answers

The magic method polymorphic_url.

When you call link_to, redirect_toetc., and you do not pass a string or a hash of routing parameters, Rails will eventually call this method.

Active Record ( Active Model) model_name, ActiveMethod:: Name, "" .

(singular_route_key) , . , namespacing, .

@article.class.model_name.singular_route_key #=> 'article'

Rails ('url', 'path' ..) , article_url. ( ), , URL- .

+4

redirect_to / , , , id . , to_params /articles/{result of to_params}. , articles/new.

+3

. article -

 article GET    /articles/:id(.:format)      articles#show

, - redirect_to @article, , .

:

1). .

2) , redirect_to @article .

3) , , , .

4) The view displays the view based on the route redirected by the controller.

+2
source

Your controller has

@article = Article.find(params[:id]) 

redirect_to @article

So @articlecontains an array of idsarticles. And also you have/articles/:id(.:format) articles#show

Therefore, whenever a specific one is updated Article, it is reinstalled in the corresponding article on the basis :idthat it contains @article.

In your case, you updated the article using id = 2, so the route/artcles/2

+2
source

Source: https://habr.com/ru/post/1536589/


All Articles