11--rails Data Interaction 3

Source: Internet
Author: User

Currently we have completed the most basic development of the user model of Weibo application, but using this user model is not convenient through the console, this lesson is to add user login and registration for the microblog application visualization function, explain the concept and use of the conversation in rails.

The user needs a password, we first add the password field to the user model, as long as two steps:

The first step is to add a field to the user model called password

The first step is more troublesome, to exit the rails console, do the following

The following files will be created automatically when you finish

Add the following code:

The code means adding a password field to the users model.

Not yet, don't forget. Working with database migrations rake db:migrate can :

?

?

第二个步骤就是在User模型里添加安全密码has_secure_password这么一个方法

第三步骤就是为password字段加上基本验证。

?

The last lesson we add new users is through the console, there should actually be pages to register users, registered users to use the site's services. Based on what we have learned earlier, we need to use the new action of the users controller to create a route for the user. We can create the users controller first, because we only create one model.

Open the controller file in the IDE:

First try to access the new action in the browser (if the page is not displayed is not running the server rails server, because the error will appear the wrong red and white page)

We can access the new action because the build controller generates its view at the same time, but we haven't added any functionality to it yet.

Open route We remove the following automatically generated routes

Change the resource route to the second line as follows:

Since it is the registration page, it is clear: a page to fill out the form information, the page has a submit button.

Let's open the new view:

Error, because after writing the view code, you also need to go to the new action to add a piece of code, the code is to give the front-end form to provide variable support:

The View code we just need to know click to register will be the user name, mailbox and password The three sets of information sent to our user controller corresponding to create such an action action can be.

还有前面添加的字段出错了正确如下,要加上_digest:

?

The following start with git to operate, do not win+r cmd window, the following directly open the project directory error, perhaps the directory is not a problem, we first-level access to the project catalog can be:

We enter a set of information try clicking Register Try:

The results are as follows:

The error is due to the creation of the create action that was submitted to the user controller when the form was submitted, but our user controller does not have a create action now,

So let's add a robust parameter, we just know that robust parameters can limit the submission of only a few fields and the other fields do not allow the submission of the line, there is a previous error, the user is preceded by @, the correct code is as follows:

This time back to the new view

Then you can see the password field is a problem, this field is added later, the possible reason is that we added did not succeed, so we delete the following third file

Then the command line enters rails g migration Addpassworddigesttousers:

Regenerate the deletion file above and add the following code:

And then execute

This is the time to re-enter the new page and click Submit, as follows:

还有我们前面的new视图代码少了一行<%=f.password_field :password %>,补充后如下:

At this time in the re-registration of the submission, the result is as follows, the password tag below the password input box:

As above, the result of our submission is back to the page of the registration page, this is the role of the following code

The word Chipeogong is because we added the verification that the validation does not pass on the red flag.

However, the user experience is very poor, because there is no wrong hint, the user will continue to enter the error, then we will add the error message:

之前我们就在控制台用过,当save失败,错误信息会保存到errors.full_messages这个字段中

Add 3 to 14 lines of code in the new view for error hints

Refresh the new page, the user name is not filled, the following random fill in some numbers, password and password confirmation did not fill in the same, the results are as follows

User name cannot be empty, email format is not valid, password and password confirmation is inconsistent, password is too short

Registration failed to write after the code, we completed the registration of the successful code to write, here we assume that the user registration is successful after the display user's profile page (this display is actually this route page, USERS/ID):

So we're going to add the jump code to the controller's save success, line 10th.

That's not going to work, because we haven't added the user profile page yet, and it's easy to add.

First add show this action in the user controller, the inside code is also very simple is based on the route of the ID (it saved to the params inside), we find and save according to the ID of the variable @user inside. Lines 16th through 18th.

Then go to the show page under the new Users folder and add the code:

This time we refresh the new page and enter Sundi,[email protected],1234567,1234567

Results as if the input is not in the normal display of the page, the original page code is wrong, <% after the Write =, modified as follows (with BR does not matter, BR is a newline):

This time indicates that our registration function can run normally, with the registration function below we also need a login function, the realization of the landing function involves a focus of this lesson "session":

When we log on to a website, the default is to log on to the account without leaving the site, so you can access any page later without having to log in again. In fact, this is the kind of technology that the conversation keeps, so what is a conversation? We can understand that the relationship between the user's browser and the rails service is maintained, keeping the login status of some users and the user's browsing information and so on.

So how does rails implement conversational functionality?

Rails uses sessions to implement a session, and rails itself provides a way for the user to call directly.

?

Session: In a computer, especially in a network application, called"Session Control". SessionObject stores the information that is required for a specific user session. This way, when the user is in the application'sWebwhen a page jumps between pages, it is stored inSessionThe variables in the object are not lost, but persist throughout the user session. When a user requests an application from theWebpage, if the user does not yet have a session, theWebthe server will automatically create aSessionobject. When the session expires or is discarded, the server terminates the session. Sessionone of the most common uses of objects is to store the user's preferences. For example, if a user indicates that they do not like to view a graphic, they can store that information in theSessionobject. About usingSessionFor more information about objects, seethe ASPApplication"part of"managing Sessions". Notesession state is only supportedCookiesbrowser is reserved.

?

So now that we know the concept of session, we're going to implement a conversational function, first add a session controller and add an action inside it called NEW:

Then we'll add the routing information:

Remove the route for the second line of code first

Add three routes, the new, create, and destroy actions, and the code 5th 6th 7th:

The new action shows the user the landing page (just like the new action in the registration), which creates a new session (which is equivalent to the creation of the registered user in the register), and destroy is used to destroy or delete the user's login session, which is what we normally call an exit session.

After completing this section, we also want to have a landing page, as follows is the auto-generated new view:

To change, the code means to provide users with a login form, when the user clicks the login button will be able to submit the login information to create this action (this we have seen in the registration page before, very convenient), We just need to know that this is used to display the login box fill in the information click Submit to submit the input information to the backend:

Next we open the sessions controller:

Add an action in the inside called Create, first of all we want to log on the most basic is to find the existence of this user, if there is to verify that the password is not correct, to find the user we use the find_by email this field to find, And we cast the fields that the user entered into lowercase before we find them.

(email:params[:session][:email].downcase),前面是数据库中的email,后面是用户的输入对应params里保存的session参数的该参数里面的[:email]字段

Then it is to judge that the user exists and that the password is incorrect.

session[: user_id]=@user. ID# This sentence is actually the current use of the @user the. ID is saved to the session variable's: user_id field, so long as we do not destroy or empty the value, the value will persist throughout the life cycle of the rails. This can be used as the credentials of the session state, we verify that there is no such value exists to know that there is currently no session login status in the hold, and then through the user_id can determine whether the current user is landing.

When we have a user login This method, we can actually after the user registration is done directly to let the user login. How do you do it? In fact, it is very simple, the user controller after the registration method also added such a line of code on the line, such as the 10th line of code. is to save the currently used @user. ID to the session variable: The USER_ID field can remember the user's login status.

Finally, we have to do is to complete the Exit function, exit is actually very simple is to set the session empty on the line, to the session controller add a destroy method as follows:

Delete and [] no spaces are separated

We also need to add an exit button to the page, such as the one we added to the profile page, as follows

We go directly to the login page and enter the following:

Click to login:

Also note the find_by and back (cannot have spaces, otherwise as follows:

In fact, these questions are very simple, the video error, correct as follows:

Find_by front to add user.

There are also verified English is authenticate, the video was written wrong

The previous error can be found by looking at the document, document address http://doc.rubyfans.com/

Enter the URL and click on Rails v4.1.0, the upper left corner of the method name, the right is the use case, you can know we need to add the user in front of our code find_by

So the first mistake will be solved, but still the error

?

然后我们文档查找发现没有找到这个方法(rails的方法,ruby而非rails的方法自可能找不到,但这里我们已经知道要找的方法就是rails的方法,但还是没找到就知道是我们方法名拼写错误),而验证的英语是authenticate,所以我们拼写错误,我们文档找该方法试试,就能查找到该方法因为是登陆验证所以我们就点击这第一个的on GitHub(没有像前面一样简短的使用案例,因为验证需要上下文,所以我们可以点击进入GitHub里面查看该方法的定义使用形式)

The correct code is as follows:

We enter the previously registered user information click on the login will be able to correctly display the following page

This indicates that we have successfully landed. At this time we click on the log Out link above to exit, return to the following page re-login:

There is also a note, the following should be Session.delete (: user_id) brackets are not [], otherwise the error will be as follows (but we delete and the following [there is a space separated can not error, this is discovered by oneself, first remember it):

?

Click Log out to jump back to the landing page, indicating that we have successfully exited and destroyed the login session.

But there are a lot of problems here, such as hash verification is not involved, the code can be written more concise and so on.

11--rails Data Interaction 3

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.