Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

22 February 2017

Ruby on Rails | Production

Add Admin role in Production

  • Go to heroku console heroku run rails console grab the user you want to set to admin. user = User.find(id) or user = User.first and use this command to toggle the admin from false to true. user.toggle!(:admin)
  • Rails console at heroku

21 February 2017

Git | Github | Basic Knowledge

  • If we work on feature of an application, we have to be careful that changes that have been made aren't going to break the application. In Git, we have a master branch where the application is stored in production and we can also have a feature branch to work on a feature in development. Any changes made in this branch will not affect our master branch. this allows many developers to work on different features of an application without touching the application in production. 
  • to create a new branch type in this command in the application directory: git checkout -b branchName
  • To check in what branch you are currently in and to see all existing branches in git: git branch (your current location will be marked with asterisk)
  • To go back to master branch: git checkout master
  • When creating new branch, keep in mind that you cannot "git push" from your new branch. You'll have first to create a new branch in your github. You can use this one command line to set up a new branch and pushing all at once: git push --set-upstream origin yourNewBranch
  • If you're using Rubymine and you want to merge your branches. I recommend to use merging function from Rubymine interface, not from terminal. I often have merging issues wenn merging from terminal. 
  • Merging is done from the master-branch otherwise changes wont be merge to master and you'll get a message "branch is already up to date.

Useful Command Line

  • To delete a branch (if you're in master branch): git branch - d branchName
  • To delete a folder in git but not in local git rm -r --cached myFolder

Ruby on Rails | Data Base

Database

  • IDs columns are mostly generated by rails.
  • To create a single migration use this command: rails generate migration create_tableName >> e.g. rails generate migration create_articles
  • after generating migration, you'll need to add column to your table. By adding it to your migration file. When you're finished type in: rake db:migrate
  • To create table and everything related to it, you can simply type in this command line: rails generate scaffold Tablename firstColumn:dataTyp secondColumn:dataTyp >> e.g. rails generate scafold User username:string email:string
  • A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
  • To migrate your database type in: rake db: migrate
  • Migrations are a convenient way to alter your database schema over time in a consistent and easy way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent.
  • In 'rails console' you can change the data of your database using ruby code. For example, in the 'users' table you can grab any user by 'user_id' using User.find(userID) or if you want to toggle any Boolean information in your database, you can use this code: user = User.find(1) and user.toggle!(:admin) this code will change admin status of user 1 to true or false. change User and :admin to your need

Validation

  • Validations are added in model class. 
  • Example of validations of presence and length: validates :username, presence: true, length:{minimum: 3, maximum: 25}
  • Example of validations of uniqueness: validates :email, uniqueness:{case_sensitive:false}
  • If you want that all emails are to be formatted to lowercase in your database, simply add before_save {self.email = email.downcase} to your User model.
  • more example: http://guides.rubyonrails.org/active_record_validations.html

Association

  • To create foreign key association when creating scaffold, type in: rails generate scaffold TableName firstColumn:dataType secondColumn:dataType tableTobeAssociated:references >> e.g. rails generate scaffold Comment description:text user:references 
  • Now we know that association has been made between users and comments, we might want to explicit some details of association. for example we want to tell our database that a user can have many comments, we have to add this line to the User model: has_many :comments
  • If you want to associate two tables manually, you will have to make some changes to the model of each table. In the User model, we have to add has_many :articles ; and in the Article model, we have to add belongs_to :user
  • This will store the userID in your table whenever a comment is made.

 

Useful command line

  • To go to rails console for testing your database : rails console
  • To exit the console: exit
  • To see the existing routes: rake routes
  • To destroy scaffold in case you made mistakes: rails destroy scaffold TableName
  • You have to be in your app directory before using all this command.

Ruby on Rails | Secure password

To store a secure password we have do the following:
  • add gem 'bcrypt' in application gemfile
  • add has_secure_password method in model (user.rb)
  • add password_digest of type string in the table attribute (users)

Ruby on Rails | Gemfile

Useful command line

  • bundle install --without production to install the gem in development environment.

Ruby on Rails | Routes

The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.

-Rails Guide-
If you type in www.example.com in your browser, this request will be sended to your webserver. Your router (routes.rb) recognize the URLs as a root, and dispatches it to whatever Controller's action you've specified in your routes.rb file. root 'pages#home' will dispatch your request to PagesController and call the home action.

If you have a form in your page, you will need to have a route so whenever you pressed the submit button, it will understand what action to perform.

To add routes you can add this code to your routes.rb file: resources :pluralObjectName e.g. resources :photos this will create 7 different routes in your application. You can also create any route manually. for a form for example, you can add post 'users', to:users#create" with this whenever you press submit, it will call the 'create' action in the UsersController and eventually redirect user to the page you've specified in the UsersController

Ruby on Rails | Partials

If you have exactly or almost exactly the same code in different places, you can make one generic code of them and use it as a template using partials.

Examples

  • In views folder, you might have the same code for a form in  new.html.erb and edit.html.erb. You can create another file named _form.html.erb and put all the same lines of code in it. In the original place, you can replace the code with <%= render 'file_path' %> please keep in mind that the path should begin with folder name where the file is located.
  • In your partial template, you can also declare variables and you can assign the value of the variable in the target page like this <%= render 'file_path' , variableName: value %>
  • Now and then you will have the situation where the codes are exactly the same except one or two lines. Fortunately rails give us method to handle this. e.g. you want to have different label for a button; on the new page you want it to be labeled "create" and on the edit page you want it to be labeled "update". Simply modify your code into this: <%= f.submit(@user.new_record? ? "sign up" : "update your account" %>

Ruby on Rails | Action Controllers

Things to know

  • Controller are connected to the view by the actions defined in it. If you declare a variable within the action, this variable will also be accessible in the views template file. e.g. if you define a @user in users_controller, @user will also be accessible in whatever template you created in users sub-folder of views.

Ruby on Rails | Application Helper

All methods used in views muss be defined in the application_helper.rb file. Once you defined a method in application helper, it will be available in all views pages.

Ruby on Rails | Pagination

As time went by, the number of article in your blog has increased rapidly. Your articles page become very long. To solve this we can use pagination.

Steps:

  1. In your gemfile, add gem 'will_paginate','version' and gem 'bootstrap-will_paginate', 'version' change the version to current version of the gem. 
  2. bundle install --without production --If production group exists-- to install the gem. 
  3. In articles_controller, at index action, change the variable value to Article.paginate(page: params[:page], per_page: 10) If you want to show more than 10 articles, simply change the number. 
  4. Add <%= will_paginate %> wherever you want to place the pagination.

Ruby on Rails | Sessions (login logout)

How to create session in Rails

  • Create route: get 'login', to: 'sessions#new'
  • Create route: post 'login', to: 'sessions#create'
  • Create route: delete 'logout', to: 'sessions#destroy'
  • Create sessions sub folder in controllers directory, and create new file, sessions_controller.rb
  • Create new, create and destroy actions.
  • In views, create new.html.erb
  • In application_controller.rb, create current_user, logged_in and require_user actions

Ruby on Rails | Basic knowledge

Things you should know in Ruby on Rails:

  • Actions that you created in application controller will be available in all your controller but they are not available to views by default. 
  • To make those actions to be available to views, add this code in the same file: helper_method :action1, :action2, and so on. 
  • In Ruby, "foo".equal? "foo" will return false and :foo.equal? :foo will return true It works that way because strings in Ruby are mutable. Unlike strings, symbols(:foo) are immutable.
  • params[:foo] in @user = User.find(params[:id]) means to tell rails to get the ':foo' or ':id' from the URL of the page that user requested
  • In this case, params[:id] is 1

Ruby on Rails | Syntax

Important syntax you have to know:

  • <% code %> to embed Ruby code in your HTML file. 
  • <%= code %> to generate HTML code with ruby methods. 
  • !!code to convert the code into Boolean statement.  
  • Local variable will be declared as variable and instance variable will be declared as @variable
  • Local variable only exists within its scope. Declaring variables in the controller as instance variables @variable makes them available to your view. 
  • a ||= b This operator means if 'a' is undefined then assign it the value of 'b', otherwise leave it alone.
  • @current_user ||= User.find(2) this means if @current_user is undefined, assign the value of user with user_id 2 to the @current_user otherwise perform nothing.
Please check this link for more Ruby Operators

Ruby on Rails | Typing Convention

Working with databases

  • Model class name is singular, starts with uppercase. e.g. class Article < ActiveRecord::Base
  • Model file name is singular, all lowercase. e.g. article.rb
  • Table name is plural of model name, all lowercase e.g. articles

Working with Buttons and Controllers

  • Controller class name is plural and written in CamelCase e.g. class ArticlesController
  • Controller file name is also plural but separated by "_" e.g articles_controller.rb

Ruby on Rails | Bootstrapping

What you should know about using Bootstrap alongside of RoR

    • Understanding Bootstraps 12 columns grid system.
    • Combine <blockquote> and <footer>  to get awesome quote effects. 
    • With class="row" you'll get a column without padding
    • When designing responsive website, keep in mind, Bootstrap will use the smallest break point first. for eg. class="col-lg-6 col-xs-4" On ipads or tablets (medium size) col-xs-4 will be used.
    • All columns will be placed from left to right. If you want to force them to be placed more right than it should be, you can use offset attribute. class="col-lg-3 col-lg-offset-6" This will create an element that take 3 columns and place it six column from the left or from its original place .
    • Class="container" will centered your container, while class="container-fluid" will stretch the your container to cover the whole screen.    
    • To apply Bootsraps forms to rails model backed form, you'll need to modify your ruby code into something like this: <%= form_for(@variableName, :html => {class= "BootstrapFormElement", role: "form"}) do |f| %>