Using redirect_to with a specific ActiveRecord object to create a reference to this object

I am studying Michael Hartle's tutorial at http://ruby.railstutorial.org/ . This is basically a messaging app where users can post messages while others can post replies. Now I am creating Users . Inside the UsersController everything looks like this:

  class UsersController < ApplicationController def new @user = User.new end def show @user = User.find(params[:id]) end def create @user = User.new(params[:user]) if @user.save flash[:success] = "Welcome to the Sample App!" redirect_to @user else render 'new' end end end 

The author says the following lines are equivalent. What makes sense to me:

  @user = User.new(params[:user]) is equivalent to @user = User.new(name: "Foo Bar", email: " foo@invalid ", password: "foo", password_confirmation: "bar") 

redirect_to @user redirects to show.html.erb . How exactly does it work? How to find out how to go to show.html.erb ?

+6
source share
3 answers

All this is handled by the magic of the rail restful route. In particular, there is a convention that makes redirect_to specific object on the show page for that object. Rails knows that @user is the active recording object, so it interprets this as knowing that you want to go to the show page for the object.

Here are some details from the related section of the Rails Guide - Rails Routing from the Out In In. :

 # If you wanted to link to just a magazine, you could leave out the # Array: <%= link_to "Magazine details", @magazine %> # This allows you to treat instances of your models as URLs, and is a # key advantage to using the resourceful style. 

Basically, using backup resources in your routes.rb gives you β€œshortcuts” for creating URLs directly from ActiveRecord objects.

+13
source

When you look at the source code of redirect_to , you will notice that finally it will return redirect_to_full_url(url_for(options), status), try to call the url_for function with an object, suppose you have an @article object, url_for (@article), it will return as follows: " http: // localhost: 3000 / articles / 11 ", which will be a new request to this URL, and then in your routing you can also check the routes in the console by typing:

rake routes

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

so redirect_to @article will act SHOW , and render in show.html.erb . Hope answered your question.

+1
source

I would suggest reading about resource routing http://guides.rubyonrails.org/routing.html .

-3
source

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


All Articles