Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does redirect_to method work in ruby

Here is my update function, the moment something is updated it perfectly goes to 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 the redirect_to @article work and show the artiles/2/ page?

Below is 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
like image 613
Shane Avatar asked Dec 19 '22 16:12

Shane


2 Answers

The magic method is polymorphic_url.

When you call link_to, redirect_to etc. and you don't pass a string or a hash of routing options Rails will end up calling this method.

Active Record (and Active Model compliant objects) have a model_name class method that returns an ActiveMethod::Name object which has a bunch of methods for obtaining the 'correct' name for a model class for various uses.

One of those (singular_route_key) says what name is used for the model in routes. This also takes care of handling things like namespacing if you're in an engine.

In the simplest case, this boils down to

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

Rails then generates the method name from that by joining this with any prefix options and the correct suffix ('url', 'path', etc.), and ends up with a method name like article_url. It then calls that method (generated for you based on your routes file), passing the article, which returns the url for this article.

like image 142
Frederick Cheung Avatar answered Feb 16 '23 04:02

Frederick Cheung


redirect_to method checks the class of instance provided and gives you the /articles based on the model class, and path provided in routes, and then it check if the object has id or not. If the object persist in database then it checkes for to_params method on that object and add to /articles/{result of to_params}. And if the object does not persist in database then it gives you articles/new.

like image 43
jbmyid Avatar answered Feb 16 '23 05:02

jbmyid