Skip to main content

Posts

Showing posts from November, 2018

Devise concepts part #3

Previous: Devise setup Devise redirection hooks helps redirect to respective controllers of methods, performing certain actions. Devise having redirection hooks like after_sign_in_path_for or after_sign_out_path_for redirect to specified paths inside methods. Add to application controller. These devise methods redirect after sign in or sign up of a user. Few redirection hooks for demo purpose: after_sign_in_path_for is redirect to profile path after logged into the app. def after_sign_in_path_for(current_user)      profile_path end after_sign_up_path_for is redirect to profile path after register into the app. def after_sign_up_path_for(resource)      profile_path end after_sign_out_path_for is redirect to root path after logged out from the app. def after_sign_out_path_for(current_user)      root_path end Related articles: Devise setup Add custom fields to devise

Action mailer in rails

Action mailer helps to send and receive mails from rails application. Action mailer inheriting from the ActionMailer::Base Mailers works similarly like controllers. Action mailer inherit from the ActiveMailer::Base it is in app/mailers and views are associated with this mailers located in app/views/post_create(in this case) *note: controller methods having associated views even same for action mailer. The instance variable of a method available to views also. This case @user and @post are instance variable. You can find at below. Add below line inside post controller create action after the save condition. PostCreate.user_post(@post.user).deliver The above line is look for the PostCreate class and user_post method inside app/mailers. Current post user attribute passing through the PostCreate method. app/mailers/post_create.rb class PostCreate < ActionMailer::Base     default from: "xxxxxxxxx@gmail.com"     def user_post user       ...

Devise concepts part #2

Devise added to rails application in devise concepts part #1 . Now generating necessary fields to rails app in part two. Generate migration file and add fields to migration file. rails g migration  add_users_fields It will generate a migration file. Field to the migration file with add_column. class AddUsersFields < ActiveRecord::Migration[5.1]   def change     add_column :users, :username, :string     add_column :users, :first_name, :string     add_column :users, :second_name, :string   end end Run migration: rake db:migrate or rails db:migrate Now username, first name and last name added to schema under users model. Permit the new generated fields in devise through model. Add configure parameters in application_constroller.rb under controllers. before_action :configure_permitted_parameters, if: :devise_controller? Protected def configure_permitted_parameters     added_attrs = [:use...

Enums in ruby on rails

Enum attribute is maps the integers in database,  but can be queried by name . Here, we adding a status feature to post model with enums. Defined a enum in Post model enum status: [:draft, :private, :public] Add a status column to post  rails g migration add_status_to_post status:integer Above rails command generates a status column in post table with an integer type. Defined enum is array type. While we creating a post status stores default value as zero. Now, post status is draft. But, we need to update status draft to public. Write method to update status of the post in Post model. def publish_post self. status = "publish"         save! end Iterating through draft posts with publish link. The publish link assigning a post method to respective controller to update the post draft to publish <% @draft_posts.each do |post| %>       <p>          <%= post.title.truncate(30) %> ...

Secure random in rails

SecureRandom is ruby library to generate random number. It supports following methods hex base64 random_number random_bytes uuid urlsafe_base64  Examples of SecureRandom: SecureRandom accepts length (optional) attribute. Length specifies the resulting string length. Open rails console or irb. user_uid (user uniqe id) is column inside users table. Adding a secure random string to user_uid, when users are creating their account. Here, i am taking hexadecimal method for demo purpose. before_validation :assign_secure def assign_secure      if self.username.blank?          error.add(:username, "Can't be blank")          return false      end      self.user_uid = self.username[0..4] + "_" + SecureRandom.hex(5) end For user_uid username must be present. From username collecting first four letters and hexadecimal string with length five adding with under...

Devise concepts part #1

Devise is flexible authentication solution for rails with warden. Devise is signed in multiple models at same time. It very flexible and modular authentication, use only what we need. Devise having different modules like, Authenticable : Validates authenticity while user sign in. Stores passwords in encrypted format. Omiauthable : Users able to sign in with facebook, twitter, linkedin ... etc. Confirmable : It sends confirmation instructions to the user. It verify the user account. Trackable : Tracks the users ip address while sign in and track the sign in count. Recoverable : Recover the password, while user forgets passwords. Registrable : Registrable allows sign up , edit and destroy the users account. Rememberable : Remembers the user credentials while users sign in. Timeoutable : Delete user sessions at certain amount of time. Validatable :  Validates user credentials while sign up and signs in. Locable : Locks the account certain amount of time after certain f...

Working with arrays in seed file

Arrays is commonly used data structure to store collection of elements. Example: type = ["html", "css", "js", "jQuery", "Bootstrap"] Arrays can use in seed file to generate multiple rows. type.each do |name| Type.create!(name: name) end When you ruby rake db:seed, the above syntax loop through the type array and create a records in type table. The problem with syntax, it can generate duplicate rows. To void this case, we use find_or_create_by! instead of create! . type.each do |name| Type.find_or_create_by!(name: name) end

Select field in rails

Collection_select returns a select and options tags to return values of existing objects and methods class. Object is an association to another model (this case type is an object). Pass a method, value method and text method to generate options for the select field. class Reference < ActiveRecord::Base belongs_to :type end class Type < ActiveRecord::Base has_many :references end Add primary to belongs to table. Below commands generate necessary migration file rails g migration add_type_id_to_reference type_id:integer:index class AddTypeIdToReference < ActiveRecord::Migration[5.2] def change add_column :references, :type_id, :integer add_index :references, :type_id end end Finally, run rake db:migrate or rails db:migrate (rails 5). Primary key added to belongs to table Add primary key to strong parameters. private def reference_params params.require(:reference).permit(:name, :type_id) end Now add collecti...

NameError: uninitialized constant ApplicationRecord

Rails models are inheriting from ApplicationRecord in rails 5. class Post < ApplicationRecord::Base end Two ways to achieve this error. 1. Create a application_record.rb in app/models class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end 2. Inherit the models from ActiveRecord. Change ApplicationRecord::Base to ActiveRecord::Base in post model. class Post < ActiveRecord::Base end

Install ruby on rails with RVM

Ruby on rails development environment on Ubuntu. We using RVM (Ruby version manager) to install ruby and its dependencies. RVM is command line tool to easily install and manage different ruby environments. Install GPG keys to used to verify security of installation packages. gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB \curl -sSL https://get.rvm.io | bash -s stable  Install Ruby with RVM. \curl -sSL https://get.rvm.io | bash -s stable --ruby Install Rails with RVM. \curl -sSL https://get.rvm.io | bash -s stable --rails RVM basic commands which ruby - Ruby version and location rvm install <ruby version> - Install ruby rvm use <version> --default - Sets as default version