mysqldump -h HOST_NAME -u USER_NAME -p DATABASE_NAME > fittac_dev_07_01_2021.sql
Wednesday, 6 January 2021
Wednesday, 23 December 2020
Image upload by active storage
https://github.com/jeygeethan/activestorage-backblaze
Add gem:
gem 'activestorage-backblaze' is gem only user for backblaze ke liye hai.
gem "aws-sdk-s3", require: false
Image upload on backblaze:
backblaze:
service: Backblaze
bucket_name: <%= ENV['BUCKET_NAME'] %>
bucket_id: <%= ENV['BUCKET_ID'] %>
key_id: <%= ENV['KEY_ID'] %>
key_token: <%= ENV['KEY_TOKEN'] %>
Run the command:
rails active_storage:install
Followed by:
rails db:migrate
Step 2 - Update Storage Parameters
In the config/storage.yml file, uncomment the 'amazon' configuration options. Make sure to add your region and bucket name.
Add this code config/storage.yml
amazon:
service: S3
access_key_id: <%= ENV['AWS_ACCESS_KEY'] %>
secret_access_key: <%= ENV['AWS_SECRET_KEY'] %>
region: <%= ENV['AWS_RESION'] %>
bucket: <%= ENV['AWS_BUCKET'] %>
==============================================
In the config/environments/development.rb there should be a line that says:
config.active_storage.service = :local
And in the config/environments/production.rb you'll need to remove the line:
config.active_storage.service = :local
And add the line:
This is amazon
config.active_storage.service = :amazon
=============================================
This is backblaze
config.active_storage.service = :backblaze
=============================================
Add a model:
has_one_attached :featured_image
==============================================
Image upload form minio
Add this code config/storage.yml
minio_dev:
service: S3
access_key_id: <%= ENV['STORAGE_ACCESS_KEY'] %>
secret_access_key: <%= ENV['STORAGE_SECRET_ACCESS_KEY'] %>
region: <%= ENV['STORAGE_REGION'] %>
bucket: <%= ENV['STORAGE_BUCKET'] %>
endpoint: <%= ENV['Endpoint'] %>
force_path_style: true
and config/development.rb and production.rb
config.active_storage.service = :minio_dev
---------------------------------
If in case getting this erro:
undefined method `has_one_attached' for #<Class:0x000055cfabb92460> (NoMethodError)
Add this line in application.rb
ActiveSupport.on_load(:active_record) do
include ActiveStorage::Reflection::ActiveRecordExtensions
ActiveRecord::Reflection.singleton_class.prepend(ActiveStorage::Reflection::ReflectionExtension)
include ActiveStorage::Attached::Model
endOn top:
attribute :profile_image do |object|
if object.profile_pic.attached?
# ENV["API_BASE_URL"] + Rails.application.routes.url_helpers.rails_blob_url(object.profile_pic, only_path: true)
object.profile_pic.service_url
end
end
Thursday, 5 November 2020
elasticsearch Install And Setup Elasticsearch Engine On Linux
Elasticsearch install step by step
java -v
java -version
echo $JAVA_HOME
ls /usr/lib/jvm//java-
for Result
java-1.7.0-openjdk-amd64/ java-1.8.0-openjdk-amd64/ java-7-openjdk-amd64/ java-8-openjdk-amd64/
==============================================================
for run Tab ke through check karna hai: echo /usr/lib/jvm/java-8-openjdk-amd64/
==============================================================
Set environment variable:
sudo nano /etc/environment
JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/
PATH=$PATH:$HOME/bin:$JAVE_HOME/bin
export JAVE_HOME
export JRE_HOME
export PATH
============================================================
Run: echo $JAVA_HOME
For result: /usr/lib/jvm/java-8-openjdk-amd64/
===================================================================
sudo apt-get install apt-transport-https
==================================================================
wget https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
====================================================================
sudo add-apt-repository "deb https://artifacts.elastic.co/packages/6.x/apt stable main"
==================================================================
sudo apt update
=====================================
sudo apt install elasticsearch
Getting this error: sudo apt install elasticsearch
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package elasticsearch
For solve:
On terminal: wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --dearmor -o /usr/share/keyrings/elasticsearch-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/elasticsearch-archive-keyring.gpg] https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-7.x.list > /dev/null
sudo apt update
sudo apt-get install elasticsearch
sudo systemctl enable elasticsearch
------------------------------------------------
When getting this error:
sudo systemctl enable elasticsearch Synchronizing state of elasticsearch.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable elasticsearch
Then run this command: sudo systemctl is-enabled elasticsearch
---------------------------------------------
sudo systemctl start elasticsearch
Check the status: sudo systemctl status elasticsearch
====================================
sudo nano /etc/elasticsearch/elasticsearch.yml
is file me must nhi hai change karna, kyu ki default me port 9200 hota hai and host 127.0.0.1 hota hai
Only for:
Uncomment line
cluster.name: my-elasticsearch
node.name: elasticsearch-1
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
http.port: 9200
=====================================
sudo systemctl start elasticsearch
======================================
Check status:
sudo systemctl status elasticsearch.service
For this resulte
elasticsearch.service - Elasticsearch
Loaded: loaded (/usr/lib/systemd/system/elasticsearch.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2020-11-05 17:48:01 IST; 11s ago
Docs: https://www.elastic.co
Main PID: 8632 (java)
Tasks: 63
Memory: 1.2G
CPU: 59.206s
CGroup: /system.slice/elasticsearch.service
├─8632 /usr/share/elasticsearch/jdk/bin/java -Xshare:auto -Des.networkaddress.cache.ttl=60 -Des.networkaddress.cache.negative.ttl=10
└─8831 /usr/share/elasticsearch/modules/x-pack-ml/platform/linux-x86_64/bin/controller
======================================
curl -X GET http://127.0.0.1:9200
{
"name" : "elasticsearch-1",
"cluster_name" : "my-elasticsearch",
"cluster_uuid" : "OL-ZPjVBTcG4b9HlEgnOdw",
"version" : {
"number" : "7.9.3",
"build_flavor" : "default",
"build_type" : "deb",
"build_hash" : "c4138e51121ef06a6404866cddc601906fe5c868",
"build_date" : "2020-10-16T10:36:16.141335Z",
"build_snapshot" : false,
"lucene_version" : "8.6.2",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
==============================================
Link: https://www.youtube.com/watch?v=63nS1Z-pIfI
Tuesday, 19 May 2020
Export csv in rails with other table
require "csv"
========================================================
Controller:
def index
if params[:q].blank?
@clients = Client.order("client_id ASC").paginate(page: params[:page])
else
@clients = Client.joins(:profile).where(["LOWER(first_name) LIKE ? OR LOWER(last_name) LIKE ?","#{params[:q].downcase}%", "#{params[:q].downcase}%"]).paginate(page: params[:page])
end
respond_to do |format|
format.html { render :index }
format.js { render :search_users }
format.csv { send_data @clients.to_csv, filename: "Filename.csv" }
end
end
======================================================
On model:
def self.to_csv
CSV.generate(headers: true) do |csv|
csv << ["Id", "Email", "First Name", "Last Name"]
all.each do |user|
row = [user.id, user.email, user.profile.first_name, user.profile.last_name]
csv << row
end
end
end
Sunday, 10 May 2020
Search other table User Join
@admins = Admin.paginate(page: params[:page])
else
@admins = Admin.joins(:profile).where(["LOWER(first_name) LIKE ? OR LOWER(last_name) LIKE ?","#{params[:q].downcase}%", "#{params[:q].downcase}%"]).paginate(page: params[:page])
# @admins = Admin.joins(:profile).where(["LOWER(first_name) LIKE ?","#{params[:q].downcase}%"]).paginate(page: params[:page])
end
respond_to do |format|
format.html { render :index }
format.js { render :search_users }
end
def agent_search
if params[:q].present?
# @agent_name = agents.joins(:profile).where("profiles.first_name= ? ", params[:q])
@agent_name = agents.joins(:profile).where(["LOWER(first_name) LIKE ?","#{params[:q].split("=").last.downcase}%"])
# @agents_skill = agents.joins(:skills).where('skills.name IN(:search)', {search: params[:q]})
@agents_skill = agents.joins(:skills).where(["LOWER(name) LIKE ?","#{params[:q].split("=").last.downcase}%"])
@agents = (@agent_name + @agents_skill).uniq
else
@agents = agents
end
respond_to do |format|
format.js { render :agent_search }
end
end
Thursday, 9 January 2020
Authentication on jwt
$ rails new rails-jwt --api
- JWT : Token encoder / decoder with expiration time
- bcrypt : Password encryption
# Use Json Web Token (JWT) for token based authenticationgem 'jwt'
# Use ActiveModel has_secure_passwordgem 'bcrypt', '~> 3.1.7'
$ bundle install
# config/routes.rbRails.application.routes.draw do resources :users, param: :_username post '/auth/login', to: 'authentication#login' get '/*a', to: 'application#not_found' end
| class JsonWebToken | |
| SECRET_KEY = Rails.application.secrets.secret_key_base. to_s | |
| def self.encode(payload, exp = 24.hours.from_now) | |
| payload[:exp] = exp.to_i | |
| JWT.encode(payload, SECRET_KEY) | |
| end | |
| def self.decode(token) | |
| decoded = JWT.decode(token, SECRET_KEY)[0] | |
| HashWithIndifferentAccess.new decoded | |
| end | |
| end |
$ rails g model user name:string username:string email:string password_digest:string
| class User < ApplicationRecord | |
| has_secure_password | |
| mount_uploader :avatar, AvatarUploader | |
| validates :email, presence: true, uniqueness: true | |
| validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } | |
| validates :username, presence: true, uniqueness: true | |
| validates :password, | |
| length: { minimum: 6 }, | |
| if: -> { new_record? || !password.nil? } | |
| end |
$ rails g controller users
$ rails g controller authentication
| before_action :authorize_request, except: :login | |
| # POST /auth/login | |
| def login | |
| @user = User.find_by_email(params[:email]) | |
| if @user&.authenticate(params[:password]) | |
| token = JsonWebToken.encode(user_id: @user.id) | |
| time = Time.now + 24.hours.to_i | |
| render json: { token: token, exp: time.strftime("%m-%d-%Y %H:%M"), | |
| username: @user.username }, status: :ok | |
| else | |
| render json: { error: 'unauthorized' }, status: :unauthorized | |
| end | |
| end | |
| private | |
| def login_params | |
| params.permit(:email, :password) | |
| end |
Thursday, 26 December 2019
File upload on carrierwave S3
gem 'mini_magick'
gem "carrierwave"
gem 'fog'
gem "fog-aws"
==================================
Uploader on:
storage :fog
==================================
For this Storage on AWS With Fog
CarrierWave.configure do |config|
if Rails.env.development? || Rails.env.test?
config.storage = :fog
else
config.fog_provider = 'fog/aws'
config.fog_credentials = {
:provider => 'AWS', # required
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'], # required
:aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], # required
:region => ENV['REGION'], # optional, defaults to 'us-east-1'
:endpoint => "https://s3-#{ENV['REGION']}.amazonaws.com"
}
config.fog_directory = ENV['AWS_BUCKET_NAME'] # required
# config.fog_public = false
config.fog_attributes = { :cache_control => 'max-age=315576000', :expires => 1.year.from_now.httpdate }
# see https://github.com/jnicklas/carrierwave#using-amazon-s3
# for more optional configuration
end
end
For Storage on AWS
============================================================
development:
AWS_SECRET_ACCESS_KEY: xxxxxxxxxxxxxxxxxxxx
AWS_ACCESS_KEY_ID: xxxxxxxxxxxxxxxxxxxx
REGION: xxxxxxxx
AWS_BUCKET_NAME: xxxxxxx.xxx
production:
# Database
AWS_SECRET_ACCESS_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxx
AWS_ACCESS_KEY_ID: xxxxxxxxxxxxxxxx
REGION: uxxxxxxx
AWS_BUCKET_NAME: xxxxxxxx.xxx
