Saturday 18 November 2017

Send email using active jobs in rails with sendgrid credentials


step 1. rails g scaffold user name:string email:string

step 2. rails generate mailer UserMailer

step 3. put method in user mailer
   
      def welcome_email(user)
        @user = user
        mail(to: @user.email, subject: 'Welcome to My Awesome Site')
      end
step 4. need to set SMTP setting in development.rb and production.rb file
    I am sending email using sendgrid credentials.
   
    config.action_mailer.delivery_method = :smtp
      config.action_mailer.smtp_settings = {
      :user_name => 'sendgrid username',
      :password => 'sendgrid password',
      :domain => 'localhost',
      :address => 'smtp.sendgrid.net',
      :port => 587,
      :authentication => :plain,
      :enable_starttls_auto => true
     }
step 5. rails g job user

step 6. copy and paste this line or you can define according to your class mailer and method name.
   
    class UserJob < ApplicationJob
      queue_as :default

      def perform(user)
          user_email = user
        ProductMailer.welcome_email(user_email).deliver_now
      end
    end
step 7. copy and paste below line in you controller method or model method where you want to use.
   
    UserJob.set(wait: 2.minutes).perform_later(current_user)

Thursday 16 November 2017

How to use multiple query in one way

 isp_condition = []
  report_date_condition = []
  other_conditions = []
 
if params[:q].present?
            # Filttering record from date wise.
            if params[:q][:report_date_gteq].present? && params[:q][:report_date_lteq].present?
              report_date_condition = ['report_date >= ? and report_date <= ?', params[:q][:report_date_gteq], params[:q][:report_date_lteq]]
            end

              # Filters for isp and other controls for fetching record.
              params[:q].each do |k,v|
                next if k.include?("report_date")
                if k.include?("isp")
                  condition = k.split("_").last
                  case condition
                  when "contains"
                    isp_condition = ['isp like ?', "%"+v+"%"]
                  when "equals"
                    isp_condition = ['isp = ?', v]
                  when "starts_with"
                    isp_condition = ['isp like ?', v+"%"]
                  when "ends_with"
                    isp_condition = ['isp like ?', "%"+v]
                  end
                  next
                end
             
              if k.include?("equals")
                param_name = k.split('_equals').first
                other_conditions << ["#{param_name} = ?", v]
              elsif k.include?("greater_than")
                param_name = k.split('_greater_than').first
                other_conditions << ["#{param_name} > ?", v]
              elsif k.include?("less_than")
                param_name = k.split('_less_than').first
                other_conditions << ["#{param_name} < ?", v]
              end
            end
          end

ActiveAdmin custom csv file method


collection_action :csv_isp_report, method: :get do
      @data = []
      @isp_manuall = $record_arr
      @isp_manuall.map{|isp_manuall| isp_manuall.map { |isp| @data << isp}}
      @data_records = @data
      csv_string = CSV.generate do |csv|
        csv << IspReport.attribute_names
        @data_records.each do |ispr|
          csv << ispr.attributes.values
        end
      end
      send_data csv_string 
  end

in View

= link_to "CSV", csv_isp_report_admin_isp_reports_path(format: "csv")

Wednesday 19 July 2017

All kind of form validation and request

1. Please visit this link which is given below. you will find awesome solution.

http://formvalidation.io/examples/

Saturday 27 May 2017

Export and import database from heroku

Export
heroku pg:backups capture
curl -o latest.dump `heroku pg:backups public-url`

Import
heroku pg:backups capture
heroku pg:backups restore 'http://example.herokuapp.com/latest.dump' DATABASE_URL

Export specific Table Heroku
pg_dump --no-acl --no-owner -h ec2-ip.compute-.amazonaws.com -U mdvxormgnpnmne -t events --data-only d3irvpu7la5kcd > events1.dump

Import specific Table Heroku
psql -U postgres -d event-kit_development -f events1.dump

Export Db: 
pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

Import Db:
psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}



Dump only contents of db:
backup: 
pg_dump -Fc -v -f full.dump -U postgres dbname
restore: 

pg_restore -a -U postgres -d event-kit_development -Fc full.dump



pg_dumpall -g -U postgres > globals.sql
Dump schema of database:
pg_dump -Fp -s -v -f db-schema.sql -U postgres dbname
Dump contents of database:
pg_dump -Fc -v -f full.dump -U postgres dbname
Now restore.
psql -f globals.sql
psql -f db-schema.sql dbname
pg_restore -a -d dbname -Fc full.dump

Saturday 20 May 2017

Import and Export Spreadsheet and CSV file

1. rails g scaffold product title:string description:text

first you have to put gem in gemfile

gem 'roo-xls'
gem 'axlsx_rails'
gem 'zip-zip'

run bundle

In application.rb
   require 'csv'

2. In prodouct model copy and paste code

# Import spread and csv file
 def self.import(file)
 spreadsheet = open_spreadsheet(file)
   header = spreadsheet.row(1)
   (2..spreadsheet.last_row).each do |i|
     row = Hash[[header, spreadsheet.row(i)].transpose]
     product = find_by_id(row["id"]) || new
     product.attributes = row.to_hash.slice(*row.to_hash.keys)
     product.save!
   end
end

 def self.open_spreadsheet(file)
     # xlsx = Roo::Excelx.new(file.path)
    case File.extname(file.original_filename)
    when ".csv" then Csv.new(file.path, nil, :ignore)
    when ".xls" then Roo::Excel.new(file.path)
    when ".xlsx" then Roo::Excelx.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
   end
 end

# Download or export CSV and Spreadsheet
def self.to_csv(options = {})
 CSV.generate(options) do |csv|
   csv << column_names
   all.each do |product|
     csv << product.attributes.values_at(*column_names)
   end
 end
end

3. In product Controller

def index
    @products = Product.all
    respond_to do |format|
      format.html
      #Download or export csv and spreadsheet
      format.csv { send_data @products.to_csv }
      format.xls { send_data @products.to_csv(col_sep: "\t") }
    end
  end


  def import
    Product.import(params[:file])
    redirect_to root_url, notice: "Products imported."
  end

4. in route.rb

  resources :products do
    collection { post :import }
  end

5. In views products/index.html.erb

<p>
  Download:
  <%= link_to "CSV", products_path(format: "csv") %> |
  <%= link_to "Excel", products_path(format: "xls") %>
</p>

<h2>Import Products</h2>
<%= form_tag import_products_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

Important Note: When you will download spreadsheet and csv file you have to remove some column id,created_at, updated_at from both file.if you will not remove that column in you file will get error "id not null column created_at, updated_at". You make sure remove these three column(id, created_at, updated_at) in both file 

Saturday 8 April 2017

Notification in rails

Notification to all users

1. rails g model notification user_id:integer receiver_id:integer notificable_id:integer notificable_type:string body:string is_read:boolean

2. Notification model

belongs_to :user
belongs_to :receiver, class_name: "User"
belongs_to :notificable, polymorphic: true

3. User model
  has_many :notifications
  has_many :receive_notifications, class_name: "User", foreign_key: "receiver_id"

4. in home controller on view you wanna show

 def index
  @receive_notifications = current_user.receive_notifications
  @notifications = current_user.notifications
 end

5. go to header in notification windows

<% if @receive_notifications %>
Receive
<% @receive_notifications.each do |ra| %>
<%= ra.body %>
<% end %>
<% end %>
<br>
<% if @notifications %>
Send
<% @notifications.each do |ra| %>
<%= ra.body %>
<% end %>
<% end %>
6. in post controller create action.
Because post will show to all user which user has created post on that.

        User.all.each do |u|
          @post.notifications.create(user_id: current_user.id, receiver_id: u.id, body: "#{current_user.email} Posted #{@post.title}" , notificable: @post) unless u == current_user
        end

 7. route.rb
  resources :notifications

  Please note: you can make more method like

  def mark_read
  end

User follower and following in rails


















1. rails g controller user index show

in usercontroller copy and paste

  def index
@users = User.all
end

def show
@user= User.find(params[:id])
end

In user model copy and paste that code

  has_many :active_relationships,  class_name:  "Relationship",
                                   foreign_key: "follower_id",
                                   dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :following, through: :active_relationships,  source: :followed
  has_many :followers, through: :passive_relationships, source: :follower

  mount_uploader :image, AvatarUploader
  # Follows a user.
  def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
  end

  # Unfollows a user.
  def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
  end

  # Returns true if the current user is following the other user.
  def following?(other_user)
    following.include?(other_user)
  end



1. view/users/index.html

<p id="notice"><%= notice %></p>

<h1>users</h1>

<table class="table">
  <thead>
    <tr>
      <th>Name</th>
         <th>Email</th>
    </tr>

  </thead>

  <tbody>
    <% @users.each do |x| %>
     <a href="/users/<%= x.id %>">
      <tr>
        <td> <%= image_tag x.image, :size => "64x64" %></td>
        <td>     <a href="/users/<%= x.id %>"><%= x.email.split('@')[0] %></a></td>
        <td><%= x.email %></td>
        <td><div class="panel-body text-center">
              <div id="follow_form_<%= x.id %>">
                <% if current_user %>
                  <% if current_user.following?(x) %>
                    <%= render 'users/unfollow', x: x %>
                  <% else %>
                    <%= render 'users/follow', x: x %>
                  <% end %>
                <%else %>
                  <%= render 'users/follow', x: x %>
                <% end %>
              </div>
            </div>
</td>
      </tr>
     
     
    <% end %>
  </tbody>
</table>

<br>


2. view/users/show.html

<p id="notice"><%= notice %></p>
<div class=" row col-md-12">
<div class="pull-left">
<%= image_tag @user.image, :size => "64x64" %>
<p>
  <strong>Name:</strong>
  <%= @user.email.split('@')[0] %>
</p>

</div>


</div>

<div class="pull-right col-md-9">
<% if params[:user].to_s == "follower" %>
<center><h1>All Follower User</h1></center>
 <% if current_user.followers.present? %>
         <% current_user.followers.each_with_index do |follower, index| %>
         <div class="row">
         <div class="col-md-2"><%= image_tag follower.image, style: "height:50px; width:50px;", title: "#{follower.email}"%></div>
          <div class="col-md-6" style="text-align: left;"><b><%= follower.email.try(:titleize) %></b></div>
         <div class="col-md-4">
          <div class="panel-body text-center">
             <div id="follow_form_<%= follower.id %>">
               <% if current_user %>
                 <% if current_user.following?(follower) %>
                 <% if user_signed_in? && follower!= current_user %>
<%= link_to "UnFollow", unfollow_path(:id => follower.try(:id), flw: false, parent_id: current_user.id, btnID: "followerBtn"), class: "btn btn-danger btn-lg btn-block", :method => :post, :remote => 'true'%>
<% end %>
                 <% else %>
                  <% if user_signed_in? && follower!= current_user %>
<%= link_to "Follow", relationships_path(:id => follower.try(:id), flw: false, parent_id: current_user.id, btnID: "followerBtn"), class: "btn btn-success btn-lg btn-block", :method => :post, :remote => 'true' %>
<% end %>
                 <% end %>
               <% end %>
                <b>Followers (<%= follower.followers.count %>) </b>
<b>Followings (<%= follower.following.count %>) </b>
             </div>
           </div>
         </div>
         </div>
         <% end %>
          <% end %>
</div>
<%elsif params[:user].to_s == "following" %>
<center><h1>All Following User</h1></center>
<div class="modal-body">
          <% if current_user.following.present? %>
         <% current_user.following.each_with_index do |following, index| %>
         <div class="row">
         <div class="col-md-2"><%= image_tag following.image, style: "height:50px; width:50px;", title: "#{following.email}"%></div>
         <div class="col-md-6" style="text-align: left;"><b><%= following.email.try(:titleize) %></b></div>
         <div class="col-md-4">
          <div class="panel-body text-center">
             <div class="panel-body text-center">
             <div id="follow_form_<%= following.id %>">
               <% if current_user %>
                 <% if current_user.following?(following) %>
                 <% if user_signed_in? && following!= current_user %>
<%= link_to "UnFollow", unfollow_path(:id => following.try(:id), flw: false, parent_id: current_user.id, btnID: "followerBtn"), class: "btn btn-danger btn-lg btn-block", :method => :post, :remote => 'true'%>
<% end %>
                 <% else %>
                  <% if user_signed_in? && following!= current_user %>
<%= link_to "Follow", relationships_path(:id => following.try(:id), flw: false, parent_id: current_user.id, btnID: "followerBtn"), class: "btn btn-success btn-lg btn-block", :method => :post, :remote => 'true' %>
<% end %>
                 <% end %>
               <% end %>
                <b>Followers (<%= following.followers.count %>) </b>
<b>Followings (<%= following.following.count %>) </b>
             </div>
           </div>
           </div>
         </div>
         </div>
         <% end %>
          <% end %>
        </div>
<%end%>
</div>


3. view/users/_follow.html.erb

<% if user_signed_in? && x!= current_user %>
<% if !(params[:flw] == "false") %>
<%= link_to "Follow", relationships_path(:id => x.try(:id)), class: "btn btn-success btn-lg btn-block", :method => :post, :remote => 'true' %>
<% else %>
<%= link_to "Follow", relationships_path(:id => x.try(:id), flw: false), class: "btn btn-success btn-lg btn-block", :method => :post, :remote => 'true' %>
<% end %>

<% end %>
<br>
<%= render partial: "users/followers_following", locals: {x: x, params: params} %>

4. view/users/_unfollow.html.erb

<% if user_signed_in? && x!= current_user %>
<% if !(params[:flw] == "false") %>
<%= link_to "UnFollow", unfollow_path(:id => x.try(:id)), class: "btn btn-danger btn-lg btn-block", :method => :post, :remote => 'true'%>
<% else %>
<%= link_to "UnFollow", unfollow_path(:id => x.try(:id), flw: false), class: "btn btn-danger btn-lg btn-block", :method => :post, :remote => 'true'%>
<% end %>
<% end %>
<br>
<%= render partial: "users/followers_following", locals: {x: x, params: params} %>

5. view/users/_followers_following.html.erb

<% if x.present? %>
<% if x.id == current_user.id %>
<b><a href="/users/<%= current_user.id %>?user=follower">Followers (<%= x.followers.count %>)</a></b>
<b><a href="/users/<%= current_user.id %>?user=following">Followings (<%= x.following.count %>) </a></b>
<%else%>
<b>Followers (<%= x.followers.count %>)</b>
<b>Followings (<%= x.following.count %>) </b>
<%end%>
<% end %>

2. rails generate model Relationship follower_id:integer followed_id:integer

after that go to see migration

class CreateRelationships < ActiveRecord::Migration[5.0]
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end
    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
    add_index :relationships, [:follower_id, :followed_id], unique: true
  end
end

rails db:migrate

3. rails g controller Relationships create unfollow

class RelationshipsController < ApplicationController
  before_action :authenticate_user!
def create
    @user = User.find(params[:id])
    @resourceRel = current_user.follow(@user)
    # if !(@resourceRel.errors.any?)
    #   Notification.notification(current_user, nil, "follow", @user)
    # end
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end

  def unfollow
    @user = User.find(params[:id])
    @resourceRel = current_user.unfollow(@user)
    # if !(@resourceRel.errors.any?)
    #    Notification.notification(current_user, nil, "unfollow", @user)
    # end
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end
end

In Relationship model

class Relationship < ApplicationRecord
belongs_to :follower, class_name: "User"
    belongs_to :followed, class_name: "User"
    validates :follower_id, presence: true
    validates :followed_id, presence: true
    validate :ambiguity

    def ambiguity
    if self.follower_id == self.followed_id
    errors.add(:_, "you can not followed your self")
    end
    if Relationship.all.collect(&:follower_id).include?(self.follower_id) && Relationship.all.collect(&:followed_id).include?(self.followed_id)
    errors.add(:_, "ambiguity record can not create")
    end
    end
end

view/relationships/create.js.erb

<% if @resourceRel.errors.any? %>
<% @resourceRel.errors.each_with_index do |error, index| %>
alertify.message('<%= error[1] %>');
<% end %>
<% else %>

<% if params[:flw] == "false" %>
  <% if params[:id].present? %>
  <% @user = User.find(params[:id].to_i) %>
  <%else%>
<% @parent_user = User.find(params[:parent_id].to_i) %>
<%end%>
// $('.modal-backdrop').removeClass('modal-backdrop');
$('#follow_form_<%= params[:parent_id].to_i %>').html('<%= escape_javascript(render partial: "users/unfollow",locals: { x: @parent_user, params: params }) %>')
$('#<%#= params[:btnID] %>').click();
$('#follow_form_<%= @user.id %>').html('<%= escape_javascript(render partial: "users/unfollow",locals: { x: @user, params: params }) %>')
<% else %>
$('#follow_form_<%= @user.id %>').html('<%= escape_javascript(render partial: "users/unfollow",locals: { x: @user, params: params }) %>')
<% end %>
<% end %>

view/relationships/unfollow.js.erb

<% if @resourceRel.errors.any? %>
<% @resourceRel.errors.each_with_index do |error, index| %>
alertify.message('<%= error[1] %>');
<% end %>
<% else %>
<% if params[:flw] == "false" %>
<% if params[:id].present? %>
  <% @user = User.find(params[:id].to_i) %>
  <%else%>
<% @parent_user = User.find(params[:parent_id].to_i) %>
<%end%>
// $('.modal-backdrop').removeClass('fade in');
$('#follow_form_<%= params[:parent_id].to_i %>').html('<%= escape_javascript(render partial: "users/follow", locals: {x: @parent_user, params: params }) %>')
$('#<%= params[:btnID] %>').click();
$('#follow_form_<%= @user.id %>').html('<%= escape_javascript(render partial: "users/follow", locals: {x: @user, params: params }) %>')
<% else %>
$('#follow_form_<%= @user.id %>').html('<%= escape_javascript(render partial: "users/follow", locals: {x: @user, params: params }) %>')
<% end %>
<% end %>


go to route.rb

  resources :relationships, :only => [:create]
  post 'unfollow' => 'relationships#unfollow', as: :unfollow

  get '/users', to: "users#index"
  get '/users/:id', to: "users#show"

Saturday 1 April 2017

Create git_hook on AWS OR DIGITAL OCEAN

Deploy App using git_hook

First you have to login on aws server or digital ocean any one you can use

ssh -i ~/Desktop/filename.pem ubuntu(ec2-username)@92.192.192.192(your public ip)

First you have to install
1. sudo apt-get install git

And Make director
2. mkdir ~/app

Give permission to app

3. sudo chmod 777 -R app/

Go to inside app

4. cd app

Make directory

5. mkdir git_hook

Give permission

6. sudo chmod 777 -R git_hook/

Go to inside

7. cd git_hook

run this comman

8. git init –bare
open this file after that you have to copy and paste below given code and you can customize app name and ec-2 username. By default user is ubuntu or for digital ocean root.

9. sudo nano git_hook/hooks/post-receive

10.






















#!/bin/bash
while
read oldrev newrev ref
do
   
if
[[ $ref =~ .*/master$ ]];
   
then
       
echo
"Master ref received.  Deploying master branch to
production..."
       
git
–work-tree=/home/ec2-user(ubuntu)/app/yourpojectname
–git-dir=/home/ec2-user(ubuntu)/app/git_hook
checkout -f
     
#
sudo  /etc/init.d/nginx restart cd
/home/ec2-user(ubuntu)/app/yourprojectname
&&  source ~/.rvm/scripts/rvm && bundle install
&& rake db:migrate
      
sudo 
/etc/init.d/nginx restart


   
else
       
echo
"Ref $ref successfully received.  Doing nothing: only the
master branch may be deployed on this server."
   
fi
done  

11
. give permission to sudo 
sudo
sh -c 'echo "ubuntu ALL=(ALL) NOPASSWD:ALL" >
/etc/sudoers.d/90-ubuntu'
Back to local machine
Go to you project directory and run this command
1. git remote add production ubuntu@192.192.192.192:app/git_hook
after this you have to add you public key permission to your machine.
2. cat ~/.ssh/id_rsa.pub | ssh -i ~/Desktop/file.pem ubuntu@192.192.192.192 'cat >> .ssh/authorized_keys && echo "Key copied"'
And finally you will run
git status
git add .
git commit -m “message”
git push production master

Revert last commit or second last and more....

 Git revert commit_id -m 1 this command willl revert last commit  Git revert commit_id -m 2 this command will revert second commit with same...