Friday, 29 November 2024

Add Serializer

Is blog se aap serializer ka name kuchh bhi rakh sakte ho, isme mene index per RolesSerializer and show per RoleDetailsSerializer ka use kiya hai, aap chaho to kisi bhi method per kisi bhi name ka serializer use kar sakte ho, Thanks


 1. Gem

gem 'fast_jsonapi'

run: bundle

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

2. app/serializers/base_serializer.rb

class BaseSerializer

  include FastJsonapi::ObjectSerializer

end

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

3. A. app/serializers/roles/roles_serializer.rb ## serializers ke ander roles name ka folder bana bhi sakte ho or nhi bhi

module Roles

  class RolesSerializer < BaseSerializer

    attributes :id, :name

  end

end

  B. app/serializers/roles/role_details_serializer.rb 

module Roles

  class RoleDetailsSerializer < BaseSerializer

    attributes :id, :name, :created_at, :updated_at


    attribute :created_at do |object|

      object.created_at.strftime('%Y-%m-%d %H:%M:%S')

    end

  end

end

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

4. app/controllers/roles_controller.rb

class RolesController < ApplicationController
before_action :set_role, only: [:show]

def index
roles = Role.all
render json: Roles::RolesSerializer.new(roles).serializable_hash, status: :ok
end

def create
    role = Role.new(role_params)
    if role.save
      render json: Roles::RolesSerializer.new(role, meta: {message: "Role created successfully"}), status: :created
    else
      render json: { errors: { message: role.errors.full_messages } }, status: :unprocessable_entity
    end
  end

  def show
  render json: Roles::RoleDetailsSerializer.new(@role, meta: {message: "Role details"}).serializable_hash, status: 200
  end

  private

  def set_role
      @role = Role.find_by(id: params[:id])
      return render json: {errors: {message: ["Role not found."]}}, :status => :not_found if @role.blank?
    end


  def role_params
  params.require(:role).permit(:name)
  end
end

Sunday, 24 November 2024

Update ID with primary id

 create_table :apps do |t|

  t.references :company, foreign_key: true

  t.string :app_id

  t.string :app_secret

  t.boolean :status, default: false


  t.timestamps

end


Local : primary id updated

118 to 6

# There is no record of 6 id

ActiveRecord::Base.transaction do

  ActiveRecord::Base.connection.execute("ALTER TABLE apps DROP CONSTRAINT fk_rails_2701a89c0b;")

  company = Company.find(118)

  company.update!(id: 6)

  App.where(company_id: 118).update_all(company_id: 6)

  ActiveRecord::Base.connection.execute("ALTER TABLE apps ADD CONSTRAINT fk_rails_2701a89c0b FOREIGN KEY (company_id) REFERENCES companies(id);")

end


71 to 118


ActiveRecord::Base.transaction do

  ActiveRecord::Base.connection.execute("ALTER TABLE apps DROP CONSTRAINT fk_rails_2701a89c0b;")

  company = Company.find(71)

  company.update!(id: 118)

  App.where(company_id: 71).update_all(company_id: 118)

  ActiveRecord::Base.connection.execute("ALTER TABLE apps ADD CONSTRAINT fk_rails_2701a89c0b FOREIGN KEY (company_id) REFERENCES companies(id);")

end

Sunday, 17 November 2024

Add Ajax Without partial

 Routes:   

get 'zzzz' => 'controllers#zzzz', :as => 'zzzz'

------

Controllers:
  include ActionView::Helpers::FormOptionsHelper
 skip_before_action :verify_authenticity_token, only: [:zzzz]
def zzzz
    bank_id = params[:bank_id]
    bank = Bank.find_by(id: bank_id)
    if bank.present?
      modes = options_for_auth_type(bank.mode)
    else
      modes = options_for_auth_type("E-mandate facility not available for this bank")
    end
    options = options_for_select(modes)
    render json: { options: modes }
  end

----------
html.erb file
<%=simple_form_for @customer, html: { class: 'form'} do |f|%>
<%= f.select :bank_id, options_for_select(select_bank, selected: f.object.bank_id), { include_blank: "Select Bank" }, { class: "chosen-select form-control mb-2 mr-sm-2", id: "bank_name", required: true } %>

<div class="col-sm-8">
                  <% if @customer.mode.present? %>
                    <%= f.select :auth_type, options_for_select(options_for_auth_type(@customer.mode), selected: f.object.auth_type), { include_blank: "Select Authorization" }, { class: "form-control mb-2 mr-sm-2"} %>
                  <% else %>
                    <%= f.select :auth_type, options_for_select([["Debit Card",'DebitCard'],["Net Banking",'NetBanking'],["Aadhaar", "Aadhaar"]], selected: f.object.auth_type), { include_blank: "Select Authorization" }, { class: "form-control mb-2 mr-sm-2"} %>
                  <% end %>
                </div>
<% end %>
<script type="text/javascript">
$(document).ready(function() {
  $('#bank_name').on('change', function() {
    var selectedBankId = $(this).val();  // Get selected bank ID
    $.ajax({
      url: '/zzzzz', // The URL where you send the request
      method: 'GET',
      data: { bank_id: selectedBankId },
      success: function(response) {
        var modes = response.options;
        var optionsHtml = '<option value="">Select Authorization</option>';
        $.each(modes, function(index, mode) {
          optionsHtml += '<option value="' + mode[1] + '">' + mode[0] + '</option>';
        });
        $('#customer_auth_type').html(optionsHtml);
      }
    });
  });
 });
</script>