Posts

Add auto increment column in Postgres in Rails

class AddAutoIncrements < ActiveRecord::Migration def self.up add_column :designs, :custom_id, :integer execute <<-SQL CREATE SEQUENCE custom_id_seq START 1; ALTER SEQUENCE custom_id_seq OWNED BY designs.custom_id; ALTER TABLE designs ALTER COLUMN custom_id SET DEFAULT nextval('custom_id_seq'); SQL end def self.down remove_column :designs, :custom_id execute <<-SQL DROP SEQUENCE custom_id_seq; SQL end end OR Added by Active record: class AddAutoIncrements < ActiveRecord::Migration def self.up add_column :users, :custom_id, :integer ActiveRecord::Base.connection.execute("CREATE SEQUENCE users_id_seq") ActiveRecord::Base.connection.execute("ALTER SEQUENCE users_id_seq OWNED BY users.id") ActiveRecord::Base.connection.execute("ALTER TABLE users ALTER COLUMN id SET DEFAULT nextval('users_id_seq')") end end def self.down remove_column

ERROR: null value in column "id" violates not-null constraint

This is easier: ActiveRecord :: Base . connection . tables . each do | t | ActiveRecord :: Base . connection . reset_pk_sequence !( t ) end If sequence missing then create new sequence to all database table:           ActiveRecord::Base.connection.tables.each do |t|      ActiveRecord::Base.connection.execute("CREATE SEQUENCE #{t}_id_seq")   end

Setup FREE SSL using Let's Encrypt.

Setup SSL There are multiple services out there offering SSL certificates for your domain, many are paid and a couple are free. Setup SSL no matter what service you use.  Let's Encrypt  is very easy, and free, to use. Let's Encrypt is a non-profit organization backed by many tech giants. Installation Run the following commands, and follow the prompts. sudo apt-get update sudo apt-get install software-properties-common sudo add-apt-repository ppa:certbot/certbot sudo apt-get update sudo apt-get install python-certbot-nginx sudo certbot --nginx sudo certbot renew --dry-run If you go to your Vultr instance now using  HTTPS , you will see a secure website. Renewal Your newly issued certificate will expire, and will need to be renewed periodically. The easiest way to do this is to set up a cron job. sudo crontab -e 30 2 * * 1 /usr/bin/certbot renew As a final, but optional step, reboot your VM and make sure all services restart as expected.

Rspec for scopes in rails

 describe "Scopes" do       it "should be active with status_id 3" do       User.active.should include(@user)       end       it "should not be suspended without status_id 4" do           User.suspended.should_not include(@user)       end       it "should not be inactive without status_id 5" do           User.inactive.should_not include(@user)       end       it "should not be hidden without status_id 6" do           User.hidden.should_not include(@user)       end       it "should not be deleted without status_id 7" do           User.deleted.should_not include(@user)       end   end

Find all records with at least one child in rails

### Find all records with at least one child Parent . join ( :children ) . uniq . al l # or Parent . includes ( :children ) . whe re ( " children.id IS NOT NULL" ) # or Rails 5 Parent . left_outer_joins ( : children ) . where . not ( children : { id : nil } ) ### Find all records with no children Parent . includes ( :children ) . whe re ( children : { id : nil } ) # or Rails 5 Parent . left_outer_joins ( : children ) . where ( children : { id : nil } )

Backup heroku database and saved on AWS s3

Add gem "fog" Create rake file lib/tasks/db.rake namespace :db do   desc "Backs up heroku database and saved on AWS s3."   task import_from_heroku: [ :environment, :create ] do     HEROKU_APP_NAME = 'appname' # Change this if app name is not picked up by `heroku` git remote.     dump_filename = "appname_prod_#{Time.now.strftime('%d-%m-%Y')}"     c = Rails.configuration.database_configuration[Rails.env]     heroku_app_flag = HEROKU_APP_NAME ? " --app #{HEROKU_APP_NAME}" : nil     Bundler.with_clean_env do       puts "[1/4] Capturing backup on Heroku"       `heroku pg:backups capture DATABASE_URL#{heroku_app_flag}`       puts "[2/4] Downloading backup onto disk"       `curl -o tmp/#{dump_filename}.dump \`heroku pg:backups public-url #{heroku_app_flag} | cat\``       puts "[3/4] Mounting backup on local database"       # `pg_restore --clean --verbose --no-acl --no-owner -h localhost -d #

Joins parent and child tables in rails

1. Get parent objects: Alert.joins("LEFT JOIN alert_events on alert_events.alert_id =  alerts.id   ").group(' alerts.id ').select(' alerts.*') 2. Get Child Object: AlertEvent.joins("INNER JOIN alerts on  alerts.id  = alert_events.alert_id  ").group(' alert_events.id ').se lect('alert_events.*') Active record for child object AlertEvent.joins(:alert).where (alerts: {category: 'Pay'}) 3. Joins multiple tables:  @previous_seafood_items = SeafoodItem.joins("LEFT JOIN auction_items on auction_items.itemable_id = seafood_items.id and auction_items.itemable_type = 'SeafoodItem' and auction_items.auction_id is NULL")     .group('seafood_items.id')     .select('seafood_items.*')     .where(user_id: current_user.id )     .paginate(:page => params[:page], :per_page => 20)

Add progress bar to process array requests in Ruby on Rails

index.html.erb: <div class="row" id="wrapper"> <div class="progress-files-count"></div> <div class="progress">   <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"><span class="progress-files-percentage">0</span></div> </div> <table class="table">   <thead>     <tr>       <th scope="col">URL</th>       <th scope="col">EMAIL</th>       <th scope="col">STATUS</th>     </tr>   </thead>   <tbody>   <% @entries.each do |entry| %>     <tr>       <td><%=link_to entry[:link], entry[:link] %></td>       <td><span id="email-<%= entry[:id]%>"></spa

Update Ruby version on AWS elastic Beanstalk

aws elasticbeanstalk update-environment --solution-stack-name "64bit Amazon Linux 2018.03 v2.8.1 running Ruby 2.3 (Puma)" --environment-name "dev-bg-123456" --region "us-east-1" Check available stacks: aws elasticbeanstalk list-available-solution-stacks { "SolutionStacks": [ "64bit Amazon Linux 2018.03 v4.16.0 running Node.js", "64bit Amazon Linux 2018.03 v2.9.11 running PHP 5.4", "64bit Amazon Linux 2018.03 v2.9.11 running PHP 5.5", "64bit Amazon Linux 2018.03 v2.9.11 running PHP 5.6", "64bit Amazon Linux 2018.03 v2.9.11 running PHP 7.0", "64bit Amazon Linux 2018.03 v2.9.11 running PHP 7.1", "64bit Amazon Linux 2018.03 v2.9.11 running PHP 7.2", "64bit Amazon Linux 2018.03 v2.9.11 running PHP 7.3", "64bit Amazon Linux 2018.03 v2.9.15 running Python 3.6", "64bit Amazon Linux 2018.03 v2.9.15 running Python 3.4", "64bit Amazon Linux 2018

React form validation and test cases.

In Component: import React , { Component } from 'react' ; import './InputForm.css' ; class InputForm extends Component { constructor ( props ) { super ( props ); this . onFormSubmit = this . onFormSubmit . bind ( this ); this . validate = this . validate . bind ( this ); this . onInputChange = this . onInputChange . bind ( this ); this . state = { fields : {}, fieldErrors : {}, }; } onInputChange ( e ) { const fields = this . state . fields ; const newFields = {}; newFields [ e . target . name ] = e . target . value ; this . setState ({ fields : {... fields , ... newFields } }); } validate ( formData ) { const errors = {}; if (! formData . name || formData . name === '' || formData . name === null ) { errors . name = 'Please enter your name.' ; } return errors ; } onFormSubmit ( e