15--helpers method

Source: Internet
Author: User

The link_to, Form_for, and Form_tag that we talked about earlier are all helpers methods of the front-end of rails (translation is the helper method). There are a lot of helpers methods, of course, this lesson we are going to talk about the helpers method is not the front-end use of the helpers method, but the controller or model can be directly called some of the auxiliary methods, and we can customize the name of the method and some of the functions inside, This helpers method can be called a custom helpers method (we call the custom method now).

Before we talked about we can write a custom library file in the Lib folder, but this kind of file general code is very large independent into the file, exposing the interface to users to use, if it is some relatively short small method small interface want to call in the project how to do? This is where the helpers file is needed to work.

We can see the following files in the project directory:

In addition to application_helper this file is generated by default, as long as you have a controller or a resource, will automatically generate the corresponding helper file, the helper file can be used in the corresponding name of the controller file. For example, if we want to use one of our own defined interfaces (or functions) in the user controller, then we can write this interface in the corresponding Users_helper file, and in the base class of our controller Application_ CONTROLLER.RB contains our users_helper so that you can use this method in the user controller.

Let's take a look at the example of using the helpers file in the controller:

The following session controller and user controller have such a sentence, the ID of the logged-in user is saved into the user_id parameter of the session variable, we have two places to use this function: 1 is the successful landing after the use of this function, 2 is registered after the successful use of this feature (because we realized that the user registration is directly logged in the state)

Then we use the Helpers file (the file name is helper not s) to implement:

After adding a method, the result is as follows:

This function is to pass the @user object as the parameter user into the Log_in method, save the id attribute of the parameter user (that is, the @user object) to the USER_ID parameter of the global variable session, so that the definition of the public method is completed.

But not yet, we'll have to include the Sessions_helper.rb file in the Application_controller.rb file, and change it as follows:

Add the 5th line directly as follows (will automatically prompt sessionshelper, this is the Sessions_helper file, although the case underline inconsistent but actually refers to the same file):

然后回到注册控制器和登陆控制器文件,把session[:user_id]=@user.id替换成log_in @user

This helpers usage is complete, but we still need to add a few helpers methods, because our microblogging application, although the login function, but we directly in the browser input route such as Weibo show page of the route can be directly accessed (directly skip login and registration can also be accessed), So it needs to be perfected.

We need to add a function, that is, to enter a page to determine if you do not log in, if you do not login to force the page to the landing page.

The first step is to add a method that returns the current user, because we are now returning the user how to do it? is to find the user_id of the session, but this is not good we need to use helpers file to improve:

Add line 6th to 9th as follows

There are also find users can use Find can also use find_by, the parameters are ID, but the difference is that the find fails the search throws an exception, and find_by returns nil, and what we need here is to return nil instead of throwing an exception is directly the wrong page.

We can also modify it again, because if we often call this current_user function in the project, we call to query once the database ah, very consumption of resources and slow. So we can judge before the query @current_user this variable exists, if there is no need to query the database directly return the result of the variable is OK, the following changes:

|| This is the same as the function of the judgment statement.

After the completion of this work we will add a common function to determine whether the user has landed, in the inside to determine the return value of Current_User this public function, if the user has logged back to true otherwise return false, the code is added as follows line 11th to 15th

There is the addition of the common function log_in, we must also add a logout method, we add the Log_out method represents the logout (line 17th to 19th), the Logout code line 18th we said before, as long as the session to keep the conversation user_id delete the line, And do not forget to put the @current_user variable empty, otherwise you log_out inside the log out but @current_user variable there is content so Current_User method will return to the previous user, which is certainly not possible:

The complete code is as follows, note that we have added the Sessionshelper in the Application_controller.rb file (so add a new public function can be used directly in the session controller does not need to go inside contains):

In this way, we can use logged_in in the project,

Then we go back to the sessions controller, first to modify the destroy code (this code is used to exit the login user):

Modify the time we first to determine whether the user is logged on, if we are to exit the operation, change the following:

So where else are we going to change it? We should go to those who have the corresponding view of the action to determine whether there is a login, you can access or forcibly return to the landing page.

It is also very simple, for example, we look at the user controller show this action (that is, to display the users ' personal page):

We add a judgment statement inside to determine if there is no login, you can access otherwise force return to the root page, after the change as follows:

Then we'll change the root address of the next route:

The original root address is as follows: Posts's index page

Change to landing page:

So what is the landing page route? is related to session-keeping sessions, not the browser input route Oh, we have written in the Routes.rb file before, as found below

So we know that the root page route is changed to the following:

Then we go back to the browser and refresh the following page:

The result is forced back to the root page (because we changed the root page to the landing page):

Then our browser input HTTP://LOCALHOST:3000/USERS/4 results still return to the landing page:

Because the others have not yet been added, we can enter other page routes or access

The following error is not inaccessible, but the record does not exist

You can also visit and other pages:

This allows us to enforce that you cannot access certain pages, unless you log in first, but if you do not log in a lot of pages can not access, then we go to each page corresponding action to write a judgment statement is very troublesome. Then there is no such a method, let us only in a controller (a controller has multiple corresponding view of the action) can be determined once, to specify which pages need to jump back to the landing page (that is, which pages need to be logged in order to access) This we do not speak first, All we need to know now is to add the following judgment in every place we have to deal with:

if logged_in? 

redirect_to root_url #跳转到根页面


Remember that root page routing is http://localhost:3000/, and we set the root page to the landing page, so the Http://localhost:3000/login route is the same as the previous route.

Now there is a problem, we enter and click Login

Find out when you click or skip back to this page:

Let's keep this question.


15--helpers method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.