Tuesday, 1 October 2024

Asymmetric encryption in Ruby On Rails OR Private Public key encryption

public_key.pem and private.key

public_key_pem = File.read(ENV['LOCAL_PUB_KEY'])

public_key = OpenSSL::PKey::RSA.new(public_key_pem)

data_to_encrypt = "Hello arvind"

encrypted_data = public_key.public_encrypt(data_to_encrypt)

private_key_pem = File.read(ENV['LOCAL_PRI_KEY'])

private_key = OpenSSL::PKey::RSA.new(private_key_pem)

decrypted_data = private_key.private_decrypt(encrypted_data)

---------------------------------------------

public_key.der and private.key

public_key_pem = File.read(ENV['LOCAL_PUB_KEY_DER'])

public_key = OpenSSL::PKey::RSA.new(public_key_pem)

data_to_encrypt = "This is the message to be encrypted"

encrypted_data = public_key.public_encrypt(data_to_encrypt)

private_key_pem = File.read(ENV['LOCAL_PRI_KEY'])

private_key = OpenSSL::PKey::RSA.new(private_key_pem)

decrypted_data = private_key.private_decrypt(encrypted_data)

---------------------------------------------

public_key.cer and private.key

public_key_pem = File.read(ENV['LOCAL_PUB_KEY_DER'])

public_key = OpenSSL::PKey::RSA.new(public_key_pem)

data_to_encrypt = "Rinku"

encrypted_data = public_key.public_encrypt(data_to_encrypt)

private_key_pem = File.read(ENV['LOCAL_PRI_KEY'])

private_key = OpenSSL::PKey::RSA.new(private_key_pem)

decrypted_data = private_key.private_decrypt(encrypted_data)

---------------------------------------------

public_key.cer and private.der

public_cer = File.read('./public_key.cer')

public_key = OpenSSL::PKey::RSA.new(public_cer)

data_to_encrypt = "Rinku k"

encrypted_data = public_key.public_encrypt(data_to_encrypt)

private_der = File.read('./private.der')

private_key = OpenSSL::PKey::RSA.new(private_der)

decrypted_data = private_key.private_decrypt(encrypted_data)

----------------------------------------------------

Hybrid Encryption: Combining Symmetric and Asymmetric Techniques

require 'openssl'

symmetric_key = OpenSSL::Cipher.new('AES-256-CBC').random_key

cipher = OpenSSL::Cipher.new('AES-256-CBC')

cipher.encrypt

cipher.key = symmetric_key

encrypted_data = cipher.update("Rinku") + cipher.final

rsa_public_key = OpenSSL::PKey::RSA.new(File.read('./public_key.cer'))

encrypted_symmetric_key = rsa_public_key.public_encrypt(symmetric_key)

rsa_private_key = OpenSSL::PKey::RSA.new(File.read('./private.der'))

decrypted_symmetric_key = rsa_private_key.private_decrypt(encrypted_symmetric_key)

decipher = OpenSSL::Cipher.new('AES-256-CBC')

decipher.decrypt

decipher.key = decrypted_symmetric_key

decrypted_data = decipher.update(encrypted_data) + decipher.final

puts decrypted_data  # "Secret message"

--------------------------------------------------------------

Asymmetric encryption in Ruby On Rails OR Private Public key encryption

require 'openssl'

require 'base64'

public_key_file = 'public.pem';

string = 'Hello World! fff';

public_key = OpenSSL::PKey::RSA.new(File.read('./public_key.cer'))

encrypted_string = Base64.encode64(public_key.public_encrypt(string))

to

encrypted_string = public_key.public_encrypt(string)  Green wali ek sath kaam karegi

print encrypted_string, "\n"

password = 'boost facile'

private_key = OpenSSL::PKey::RSA.new(File.read('./private.der'),password)

string = private_key.private_decrypt(Base64.decode64(encrypted_string))

to

string = private_key.private_decrypt(encrypted_string)

print string, "\n"


Monday, 30 September 2024

Video upload on youtube from rails application

Video upload on youtube from rails application


1. Gemfile.lock

gem 'google-api-client', '~> 0.43'

gem 'signet'

gem "image_processing"

gem "oauth2"

gem 'omniauth-oauth2'

gem 'omniauth-google-oauth2'

gem 'google-apis-youtube_v3'


2. config/routes.rb


Rails.application.routes.draw do

  get '/auth/:provider/callback', to: 'sessions#google_oauth2_callback'

  get '/auth/failure', to: redirect('/')

  get '/youtube_session_logout', to: 'sessions#youtube_session_logout'

  # Your other routes...

end


3. SessionsController


# app/controllers/sessions_controller.rb

class SessionsController < ApplicationController

  def google_oauth2_callback

    auth = request.env['omniauth.auth']

    # Store tokens in session for future requests

    session[:google_token] = auth.credentials.token

    session[:google_refresh_token] = auth.credentials.refresh_token if auth.credentials.refresh_token

    session[:google_expires_at] = Time.at(auth.credentials.expires_at)

    session[:is_youtube] = true

    session[:email] = auth.info.email


    redirect_to root_path, notice: 'Connected to YouTube!'

  end


  def youtube_session_logout

    youtube_service = YouTubeService.new(session)

    # Call the logout method to revoke the token and clear session data

    youtube_service.logout(session)

    # Optionally, redirect the user to the homepage or a sign-in page

    redirect_to root_path, notice: "You have been logged out from YouTube."

  end


  def failure

    redirect_to root_path, alert: "Authentication failed, please try again."

  end

end


4. config/initializers/omniauth.rb

# config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do

  provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], scope: 'userinfo.email, youtube.upload',access_type: 'offline', prompt: 'consent'

    # provider :google_oauth2, "#{ENV['GOOGLE_CLIENT_ID']}", "#{ENV['GOOGLE_CLIENT_SECRET']}", scope: 'userinfo.profile,youtube,email', provider_ignores_state: true, prompt: :consent


end

OmniAuth.config.allowed_request_methods = %i[get] #ye line bhi add karna hai isi file me (omniauth.rb)


----------------------------------------------------------------------

5. app/services/you_tube_service.rb


require 'google/apis/youtube_v3'

require 'google/api_client/client_secrets'


class YouTubeService

    GOOGLE_REVOKE_TOKEN_URL = 'https://oauth2.googleapis.com/revoke'


  def initialize(session)

    @service = Google::Apis::YoutubeV3::YouTubeService.new

    @service.authorization = Signet::OAuth2::Client.new(

      client_id: ENV['GOOGLE_CLIENT_ID'],

      client_secret: ENV['GOOGLE_CLIENT_SECRET'],

      token_credential_uri: 'https://oauth2.googleapis.com/token',

      access_token: session[:google_token],

      refresh_token: session[:google_refresh_token],

      expires_at: session[:google_expires_at]

    )

    refresh_token_if_needed(session)

  end


  def upload_video(file_path, title, description)

    begin

      video = Google::Apis::YoutubeV3::Video.new(

      snippet: {

        title: title,

        description: description

      },

      status: {

        privacy_status: 'public' # or 'private'

      }

    )


    File.open(file_path, 'rb') do |file|


      @service.insert_video('snippet,status', video, upload_source: file, content_type: 'video/*')

    end

    rescue StandardError => e

      Rails.logger.info "****************#{e.message}"

    end

    

  end


  def logout(session)

    revoke_token(session[:google_token])

    # Clear session information

    session.delete(:google_token)

    session.delete(:google_refresh_token)

    session.delete(:google_expires_at)

    session[:is_youtube] = false

    session.delete(:email)

  end


  private


  def refresh_token_if_needed(session)

    if @service.authorization.expired?

      @service.authorization.refresh!

      session[:google_token] = @service.authorization.access_token

      session[:google_refresh_token] = @service.authorization.refresh_token

      session[:google_expires_at] = @service.authorization.expires_at

    end

  end


  def revoke_token(token)

    uri = URI(GOOGLE_REVOKE_TOKEN_URL)

    response = Net::HTTP.post_form(uri, { token: token })

    

    unless response.is_a?(Net::HTTPSuccess)

      raise "Token revocation failed: #{response.body}"

    end

  end

end



6. app/views/layouts/application.html.erb

<% if session[:is_youtube] %>

  <%= link_to "Logout from YouTube:- #{session[:email]}", youtube_session_logout_path, method: :get %> ||

  <span><%= session[:google_expires_at] %></span>

<% else %>

  <%= link_to "Connect with YouTube", "/auth/google_oauth2" %>

<% end %>



7. Go to Google

https://accounts.google.com/InteractiveLogin/signinchooser?continue=https%3A%2F%2Fconsole.cloud.google.com%2Fapis%2Fcredentials&followup=https%3A%2F%2Fconsole.cloud.google.com%2Fapis%2Fcredentials&osid=1&passive=1209600&service=cloudconsole&ifkv=ARpgrqdZOpQ_ekvU2Vp4_Id4NGAvDWflX7oG6tg6QEUEx-wmEmFM_lZfTWmv8pO9lpNrtmAhcXFeDw&ddm=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin


7.1. login account

  2. Create project

  3. Go to API & Services >> Credentials

  4. then click "CREATE CREDENTAILS" ye button top center me hai

  5. "CREATE CREDENTAILS" click karne ke baad, yaha per apko multiple option show hoge

  5.1. API key created >> isko bhi create kar sakte ho requerment ho to

  5.2. OAuth client ID >> click on this >> choose "External"

  5.3. "OAuth consent screen": isme 1.  Application home page me "http://localhost:3000" 

            2. Add privacy policy

                                                          3. Add Authorized Domain: "ebay.com" ye kuchh bhi ho sakta hai

                                                          4. Developer contact information: "email.com"

8. Add call bank url

8.1. Goto Credentials >> "OAuth 2.0 Client IDs" >> jis Auth ki ID use kar rhe ho us per click karna hai >> "Authorized redirect URIs" add URI "http://localhost:3000/auth/google_oauth2/callback" >> then save

Sunday, 29 September 2024

Getting (time ago )Data created_at or updated_at day_ago time

 In the model:


include ActionView::Helpers::DateHelper

def days_ago

    # -----------------------------------------------------

    # if self.uploaded_at

    #   time_ago_in_words(self.uploaded_at) + " ago"

    # else

      # time_ago_in_words(self.created_at) + " ago"

    # end

    # time_diff = Time.current - created_at

    # ----------------------------------------------------

    # if time_diff < 60

    #   "#{time_diff.to_i} seconds ago"

    # else

    #   time_ago_in_words(created_at) + " ago"

    # end

    # ----------------------------------------------------

    time_diff = Time.current - created_at


    if time_diff < 60

      "#{time_diff.to_i} seconds ago"

    elsif time_diff < 3600

      "#{(time_diff / 60).to_i} minutes ago"

    elsif time_diff < 86400

      "#{(time_diff / 3600).to_i} hours ago"

    elsif time_diff < 30.days

      "#{(time_diff / 86400).to_i} days ago"

    elsif time_diff < 1.year

      "#{(time_diff / 1.month).to_i} months ago"

    else

      "#{(time_diff / 1.year).to_i} years ago"

    end

  end


-------------------------------------------------

Console Or Views pages

p = Product.last

p.days_ago

Monday, 5 August 2024

Could not detect rake tasks on HEROKU

 1. .gitignore file me ye add karna hai

node_modules

yarn.lock

2. nvm install 20.9.0


3. nvm  use 20.9.0


BUNDLED WITH

   2.3.25


check this history:

heroku buildpacks:set heroku/ruby

 2155  node -v

 2156  nvm  use 20.9.0

 2157  nvm install 20.9.0

 2158  nvm  use 20.9.0

 2159  git status

 2160  git add node_modules/.yarn-integrity

 2161  git add .gitignore

 2162  git commit -m"Remove Node modukle"

 2163  yarn install

 2164  git status

 2165  git add .gitignore

 2166  git rm --cache yarn.lock

 2167  git status

 2168  git commit -m"Remove yarn"

 2169  git push origin(name)   isme branch ka use nhi karna hai

 2170  heroku config:get BUILDPACK_URL

 2171  heroku config:get BUILDPACK_URL --app equinemd

 2172  heroku buildpacks

 2173  heroku buildpacks --app equinemd

 2174  heroku buildpacks:set heroku/ruby --app equinemd

 2175  curl https://cli-assets.heroku.com/install-ubuntu.sh | sh

 2176  bundle lock --add-platform x86_64-linux

 2177  git status

Thursday, 25 July 2024

Js validation and password show and hide in admin side OR Web page

1. app/admin/app_users.rb
form do |f|

    render 'form', context: self, f: f

  end

-------------------------------------------------------

2. IN Active admin side : app/views/admin/users/_form.html.erb

<% context.instance_eval do

    semantic_form_for resource, url: admin_users_path do

  # f.semantic_errors *f.object.errors.keys

      f.inputs 'Details' do

f.input :first_name, required: true, :as => :string, label: "Name"

      f.input :full_phone_number, input_html: {maxlength: 12, onkeypress: "return onlyNumberKey(event)"}, required: true

      f.input :email, required: true

      f.input :user_name, required: true

      f.input :activated, label: "Activate",input_html: {checked: true}

      f.input :role, as: :select, collection: BxBlockRolesPermissions::Role.all, include_blank: false, :input_html => { :width => 'auto', "data-placeholder" => 'Click' }

      f.input :password, label: "Password",:input_html => {id: "account_password"}, required: true

      f.hidden_field :temporary_password


  end

f.inputs 'Organization Profile' do

    f.semantic_fields_for :profile do |s|

  s.input :name, label: "Organization name"

      s.input :business_location

      s.input :address

      s.input :email

      s.input :contact_no

      s.input :license_no

      s.input :fiscal_year

      s.input :city

      s.input :state

      s.input :pin_code

      s.input :website_url

      s.input :fax_no

      s.input :profile_pic, as: :file

    end

  end


  f.actions

  end

  end

%>


<script type="text/javascript">

$('#account_password').after("<label class='password_show_hided' onclick='password_show_hide();'><i class='fas fa-eye' id='hide_eye'></i><i class='fas fa-eye-slash' id='show_eye' style='display: none;'></i></label>");

function onlyNumberKey(evt) {

    var ASCIICode = (evt.which) ? evt.which : evt.keyCode

    if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))

      return false;

    return true;

  }

$(document).ready(function() { 

  jQuery.validator.addMethod("lettersonly", function(value, element) {

    return this.optional(element) || value.match(/^[a-zA-Z]+$/);

  });

  jQuery.validator.addMethod("fullPhoneNo", function(phone_number, element) {

    phone_number = phone_number.replace(/\s+/g, "");

    return this.optional(element) || phone_number.length == 12 && 

    phone_number.match(/^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/);

  });

  jQuery.validator.addMethod("checkEmail", function(value, element) {

    return this.optional(element) || value.trim().match(/^(([^<>()\[\]\\.,;:\s@"']+(\.[^<>()\[\]\\.,;:\s@"']+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);

  });

  jQuery.validator.addMethod("checkUsername", function(value, element) {

    return this.optional(element) || value.match(/^[A-Za-z0-9]*$/);

  });


  jQuery.validator.addMethod("checkPassword", function(value, element) {

    return this.optional(element) || value.match(/^(?=.*[A-Z])(?=.*[#!@$&*?<>',\[\]}{=\-)(^%`~+.:;_])(?=.*[0-9])(?=.*[a-z]).{8,}$/);

  });


  $("#new_account").validate({

    rules:{

      'account[first_name]':

      {

        required: true,

        minlength: 3,

        lettersonly: true

      },

      'account[full_phone_number]':

      {

        required: true,

        fullPhoneNo: true,

        minlength: 12,

        maxlength: 12

      },

      'account[email]':

      {

        required: true,

        checkEmail: true

      },

      'account[user_name]':

      {

        required: true,

        checkUsername: true

      },

      'account[password]':

      {

        required: true,

        checkPassword: true

      },

    },messages:{

'account[first_name]':{

required: "<p class='inline-errors'>Please enter first name</p>",

minlength: "<p class='inline-errors'>Please enter valid first name</p>",

lettersonly: "<p class='inline-errors'>Please enter valid first name</p>"

},

'account[full_phone_number]':{

required: "<p class='inline-errors'> Please enter mobile number</p>",

fullPhoneNo: "<p class='inline-errors'>Please enter valid mobile number</p>",

minlength: "<p class='inline-errors'>Please enter valid mobile number</p>",

maxlength: "<p class='inline-errors'>Please enter valid mobile number</p>"

},

'account[email]':{

required: "<p class='inline-errors'>Please enter email id</p>",

checkEmail: "<p class='inline-errors'>Please enter a valid email address.</p>"

},

'account[user_name]':{

required: "<p class='inline-errors'>Please enter user name</p>",

checkUsername: "<p class='inline-errors'>Please enter valid user name</p>"

},

'account[password]':{

required: "<p class='inline-errors'>Please enter password</p>",

checkPassword: "<p class='inline-errors'>Please enter a valid password (ex: Aa@12345, min. length 8)</p>"

}

    }

  });

  $("#edit_account").validate({

    rules:{

      'account[first_name]':

      {

        required: true,

        minlength: 3,

        lettersonly: true

      },

      'account[full_phone_number]':

      {

        required: true,

        fullPhoneNo: true,

        minlength: 12,

        maxlength: 12

      },

      'account[email]':

      {

        required: true,

        checkEmail: true

      },

      'account[user_name]':

      {

        required: true,

        checkUsername: true

      },

      'account[password]':

      {

        checkPassword: true

      },

    },messages:{

'account[first_name]':{

required: "<p class='inline-errors'>Please enter first name</p>",

minlength: "<p class='inline-errors'>Pleaseee enter valid first name</p>",

lettersonly: "<p class='inline-errors'>Please enter valid first name</p>"

},

'account[full_phone_number]':{

required: "<p class='inline-errors'> Please enter mobile number</p>",

fullPhoneNo: "<p class='inline-errors'>Please enter valid mobile number</p>",

minlength: "<p class='inline-errors'>Please enter valid mobile number</p>",

maxlength: "<p class='inline-errors'>Please enter valid mobile number</p>"

},

'account[email]':{

required: "<p class='inline-errors'>Please enter email id</p>",

checkEmail: "<p class='inline-errors'>Please enter a valid email address.</p>"

},

'account[user_name]':{

required: "<p class='inline-errors'>Please enter user name</p>",

checkUsername: "<p class='inline-errors'>Please enter valid user name</p>"

},

'account[password]':{

checkPassword: "<p class='inline-errors'>Please enter a valid password (ex: Aa@12345, min. length 8)</p>"

}

    }

  });

});

function password_show_hide() {

  var x = document.getElementById("account_password");

  var show_eye = document.getElementById("show_eye");

  var hide_eye = document.getElementById("hide_eye");

  // hide_eye.classList.remove("d-none");

  if (x.type === "password") {

    x.type = "text";

    show_eye.style.display = "block";

    hide_eye.style.display = "none";

  } else {

    x.type = "password";

    show_eye.style.display = "none";

    hide_eye.style.display = "block";

  }

}

$('#account_password').keyup(function() {

    var password = this.value;

    $("#account_temporary_password").val(password);

});

</script>

<style type="text/css">

#account_first_name-error, #account_last_name-error, #account_full_phone_number-error, #account_user_name-error {

width: 100% !important;

    padding-bottom: 12px !important;

}

#account_password-error {

width: 100% !important;

}

#account_email_input #account_email-error{

width: 100% !important;

    padding-bottom: 12px !important;

    color: #932419;

font-weight: bold;

margin: 0.3em 0 0 20%;

}

#account_email_input #account_email-error p.inline-errors{

margin: auto !important;

}

.password_show_hided{

font-weight: bold;

margin: -1.9em 0 0 91%;

width: 22px;

    cursor: pointer;

    position: absolute;

    text-align: center;

}


.fas{

line-height: unset !important;

}

@media only screen and (max-width: 1060px) {

  .password_show_hided{

margin: -1.9em 0 0 90%;

}

}


@media only screen and (max-width: 958px) {

  .password_show_hided{

margin: -1.9em 0 0 89%;

}

}


@media only screen and (max-width: 444px) {

  .password_show_hided{

margin: -1.9em 0 0 72%;

}

}

</style>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous" />

Tuesday, 18 June 2024

get records from two date rails

if params[:start_date].present? && params[:end_date].present?
        userids = UserIncentive.where("created_at >= ? AND created_at <= ?", params[:start_date].to_date, params[:end_date].to_date).map(&:user_id).uniq
      else

How to use elasticsearch for searching step by step

  1. Add the elasticsearch and elasticsearch-model gems: Add these to your Gemfile:

    ruby
    gem 'elasticsearch-model' gem 'elasticsearch-rails'

    Then run:

    sh
    bundle install

Step 3: Configure Elasticsearch in Rails

  1. Create an Elasticsearch Configuration File: Create a file named config/elasticsearch.yml with the following content:

    yaml
    development: url: http://localhost:9200 test: url: http://localhost:9200 production: url: <your-production-elasticsearch-url>
  2. Create an Initializer: Create an initializer file config/initializers/elasticsearch.rb:

    ruby
    Elasticsearch::Model.client = Elasticsearch::Client.new host: ENV['ELASTICSEARCH_URL'] || 'localhost:9200'

Step 4: Integrate Elasticsearch with Your Models

  1. Include Elasticsearch in Your Model: Let's say you have a Post model. Include Elasticsearch and its necessary modules:

    ruby
    class Post < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks end
  2. Customize Your Elasticsearch Index: You can customize how your model is indexed. Add an index definition to your model:

    ruby
    class Post < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks settings do mappings dynamic: false do indexes :title, type: :text, analyzer: 'english' indexes :content, type: :text, analyzer: 'english' end end end
  3. Index Existing Records: After setting up your model, you need to index your existing records:

    ruby:
    Post.import # for importing all records to Elasticsearch

Step 5: Implement Search Functionality

  1. Add a Search Method in Your Model:

    ruby:
    class Post < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks settings do mappings dynamic: false do indexes :title, type: :text, analyzer: 'english' indexes :content, type: :text, analyzer: 'english' end end def self.search(query) __elasticsearch__.search( { query: { multi_match: { query: query, fields: ['title^10', 'content'] } } } ) end end
  2. Create a Controller Action for Search: In your controller, add a search action:

    ruby;
    class PostsController < ApplicationController def search @posts = Post.search(params[:query]).records end end
  3. Add a Route for Search: In your config/routes.rb:

    ruby:
    get 'search', to: 'posts#search'
  4. Create a View for Search: Create a search view app/views/posts/search.html.erb:

    <h1>Search Results</h1> <%= form_with url: search_path, method: :get do %> <%= text_field_tag :query, params[:query] %> <%= submit_tag 'Search' %> <% end %> <% @posts.each do |post| %> <div> <h2><%= post.title %></h2> <p><%= post.content %></p> </div> <% end %>


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

after used this code i am getting this errors Elastic::Transport::Transport::Errors::NotFound in Posts#search Showing /home/bittern/Desktop/rinku/projects/simple_dummy/app/views/posts/search.html.erb where line #7 raised:

[404] {"error":{"root_cause":[{"type":"index_not_found_exception","reason":"no such index [posts]","resource.type":"index_or_alias","resource.id":"posts","index_uuid":"na","index":"posts"}],"type":"index_not_found_exception","reason":"no such index [posts]","resource.type":"index_or_alias","resource.id":"posts","index_uuid":"na","index":"posts"},"status":404}

ChatGPTThe error you are encountering, Elastic::Transport::Transport::Errors::NotFound: no such index [posts], indicates that the Elasticsearch index for your Post

Steps to Resolve the Error

  1. Create the Index: Use the import method to create the index and populate it with your existing records. Run the following command in your Rails console:

    ruby
    Run: Post.import(force: true)

    This command will create the posts index in Elasticsearch and add all existing Post records to the index.

    Ager Ye wala step chal rha hai to Second wala nhi chalana (2. Ensure Elasticsearch is Running)

  2. Ensure Elasticsearch is Running: Make sure that your Elasticsearch service is running. You can check the status of Elasticsearch with the following command:

    sh
    Run: sudo systemctl status elasticsearch

    If it is not running, start it with:

    sh
    sudo systemctl start elasticsearch
  3. Check Elasticsearch Connection: Verify that your Rails application can connect to Elasticsearch. You can do this by testing a simple query in the Rails console:

    ruby
    Post.__elasticsearch__.client.cluster.health

    This should return the health status of your Elasticsearch cluster.

  4. you can use the following steps:

    1. Delete the Existing Index: You can delete the existing index using the Rails console:

      ruby

      Run: Post.__elasticsearch__.client.indices.delete index: Post.index_name
    2. Recreate and Populate the Index: After deleting the index, recreate and populate it with:

      ruby:
      Run: Post.__elasticsearch__.create_index!(force: true) Run: Post.import