Last week, I built a blog prototype based on the twitter-like app in Rails Tutorial. Here is the 2nd note.
Create a database index on the email column, and require that the index be unique.
Add validation ‘app/models/user.rb’
Apply a gem called
bcrypt-ruby. Presence validations for the password and its confirmation are automatically added by
has_secure_password. Call method
authenticate to confirm and get user.
Generate migration and
add_column :users, :password_digest, :string to the table.
Sign in user
create a non-model backed controller
sessions. A session is a semi-permanent connection between two computers, such as a client computer running a web browser and a server running Rails. Sessions resource will use a cookie, which is a small piece of text placed on the user’s browser.
non-model backed form for sign-in, using form_tag
alternatively, using form_for(:session, url: sessions_path)
signin page above for new sessions, signing in will create a session, and signing out will destroy it
define current_user in ApplicationController and add
helper_method :current_user, :sign_in?, … to make it available to view templates. Alternatively, we can add methods in ApplicationHelper, and add
include SessionsHelper in ApplicationController to make it available in controller.
“||=” assigning to a variable if it’s nil but otherwise leaving it alone. memorization: calls the find_by method the first time current_user is called, but on subsequent invocations returns @current_user without hitting the database.
sign in user upon sign up:
add_user_id_to_post and assign user_id to new post
add in ‘app/helper/user_helper.rb’ and call <%= gravatar_for @user %>
add some styles
Require the same user
Change date format
apart from @import bootstrap in app/assets/stylesheets/custom.css.scss
flash.now #disappear as soon as there is an additional request.
when I submit blank comment, it leads to error. this is because I run the _comments.html.erb before render the error message.
add <% unless comment.body.blank? %> …. <% end %> in _comments partial.
The reason is that initializing the entire params hash is extremely dangerous—it arranges to pass to User.new all data submitted by a user. In particular, suppose that, in addition to the current attributes, the User model included an admin attribute used to identify administrative users of the site. The way to set such an attribute to true is to pass the value admin=’1’ as part of params[:user], a task that is easy to accomplish using a command-line HTTP client such as curl. The result would be that, by passing in the entire params hash to User.new, we would allow any user of the site to gain administrative access by including admin=’1’ in the web request.
<%= render ‘shared/posts’ , objects: @posts%> to reduce duplication