samedi 29 octobre 2022

Can I use javascript packages that I installed using NPM in my Rails 6 ERB files

I created a new rails 6 project and I installed some javascript packages as well using npm. but when I am in an erb file (views/posts/index.js.erb) I cannot access jquery or any of the packages I installed using npm.

Is there a way I can use JS libraries in my *.js.erb files?

vendredi 28 octobre 2022

StoreController#index is missing a template for request formats: text/html

It is showing me "StoresController#pages is missing a template for request formats: text/html" even though everything is correct, I added navbar and devise and simple forms and it was working perfectly fine in morning (about 7 hours ago), then now when i start the server it shows this error! any fixes??

stores_controller.rb

class StoresController < ApplicationController
  def index
  end
end

views/stores/index.html.erb

<h1>Store#index</h1>
<p>Find me in app/views/store/index.html.erb</p>

config/routes.rb

Rails.application.routes.draw do
  devise_for :users, controllers: { registrations: 'registrations' } 

  devise_scope :user do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end

  root 'store#index'

end

Screenshot

I tried restarting the server multiple times with different terminals, with VScode and with Git Bash both, but it didn't work and it shows the same error!

Morning it was working absolutely fine and i even added devise, simple_form and added navbar and it was working, then after 7 hours now when i started the server,it is showing me this error

mercredi 26 octobre 2022

undefined method `original_filename' for #<:storage::awsfile:>

Can't seem to identify why I would be getting a undefined method original_filename. Maybe because when upgrading ruby 3.1.2,with ruby 2.7.5 can still use this method.

Uploader

class DocumentUploader < CarrierWave::Uploader::Base
  CarrierWave::SanitizedFile.sanitize_regexp = Settings.regex.upload_filename

  def store_dir
    "uploads/event_documents/#{mounted_as}/#{model.id}"
  end
end

Model

class EventDocumentFile < ActiveRecord::Base
  mount_uploader :document_file, DocumentUploader
  validate :document_file_name

  private

  def document_file_name
    return if !document_file.file.present? || document_file.file.original_filename.length <= 70
    errors.add :document_file, I18n.t("event_documents.invalid_file_name")
  end
end

Error detail

undefined method `original_filename' for #<CarrierWave::Storage::AWSFile:0x00007fe60dfc38e8 @uploader=#<DocumentUploader:0x00007fe60dfbdc18 @model=#<EventDocumentFile

return if !document_file.file.present? || document_file.file.original_filename.length <= 70
                                                            ^^^^^^^^^^^^^^^^^^

Anyone know what's wrong with my code? thanks!

vendredi 21 octobre 2022

Ruby On Rails on Win 10

On win 10, After installing RoR 3.x and Ruby 7.x, and sqlite 3.x, the server will not start from CLI, I am not using Windows Powershell but the CMD window.

Does any part of the install of those packages require Admin window?

Does the "bin/rails server" command require Admin privileges from CLI.

Thank You

jeudi 20 octobre 2022

Join table if value is X or related table does not exist with X value

I have a users table and reporting_events table. reporting_event belongs to user. I used join on users table like.

   users.joins(:reporting_events).where(reporting_events: { name: sort_column } )

Here I get users with reporting event names as sort_column.

I want to list users if reporting_events name is sort_column or if user does't have a reporting_event with name sort_column.

I want to user order after this where clause like:

  users.joins(:reporting_events).where(reporting_events: { name: sort_column } ).group("users.id").order("count(reporting_events) #{sort_direction} nulls last")

The problem is that this returns only those users with reporting events with the sort_column name. I want to return all the users always, and to order them by count of reporting events with the name if the reporting_event exists.

mardi 18 octobre 2022

Sort by join table fields

I have a user table and a reporting events table.

reporting_event.rb

class ReportingEvent < ApplicationRecord
  belongs_to :user
  belongs_to :conversation, optional: true

  EVENT_TYPES = {
    ASSIGN_AGENT: "assign_agent",
    FIRST_RESPONSE: "first_response",
    AVERAGE_RESOLUTION_TIME: "avg_resolution_time",
    POST_CHAT_RESPONSE: "post_chat_response",
    AVERAGE_RESPONSE_TIME: "avg_response_time",
    AVERAGE_FIRST_RESPONSE_TIME: "avg_first_response_time",
    CLOSE_CONVERSATION: "close_conversation"
  }

  scope :post_chat, -> { where(name: EVENT_TYPES[:POST_CHAT_RESPONSE]) }
  scope :assignments, -> { where(name: EVENT_TYPES[:ASSIGN_AGENT]) }
  scope :resolutions, -> { where(name: EVENT_TYPES[:CLOSE_CONVERSATION]) }
  scope :avg_resolution_times, -> { where(name: EVENT_TYPES[:AVERAGE_RESOLUTION_TIME]) }
  scope :first_response_times, -> { where(name: EVENT_TYPES[:FIRST_RESPONSE]) }
  scope :avg_response_times, -> { where(name: EVENT_TYPES[:AVERAGE_RESPONSE_TIME]) }
  scope :avg_first_response_times, -> { where(name: EVENT_TYPES[:AVERAGE_FIRST_RESPONSE_TIME]) }
  scope :between_dates, -> (start_date, end_date) { where(created_at: [start_date..end_date]) }

  validates :name, inclusion: EVENT_TYPES.values
end

Reporting Event belongs to user.

I have to sort user based on reporting event assignments, resultions, avg_resolution_time etc values. For this I can make a scope in user.rb?

  scope :sort_by_average_resolution_time, ->(dir: "ASC") { joins(:reporting_events).order("reporting_events.avg_resolution_times #{dir}") }
  scope :sort_by_average_resolution_time_asc, -> { sort_by_average_resolution_time }
  scope :sort_by_approval_rate_desc, -> { sort_by_average_resolution_time dir: "DESC" }

In the controller, I want to sort the users.

  def index
    filter_service = Reports::FilterService.new(@organization, reports_filter_params)
    users = filter_service.process
    @user_reports = users.sort_by_average_resolution_time_asc.map { |agent| ReportsCarrier.new(agent, @start_date, @end_date) }
    @total_count = filter_service.total_count
  end

How do I sort by reporting_events values which belongs to user?

lundi 17 octobre 2022

unable to rake db:migrate

everyone one I am working on a Sinatra app. I am trying to use Active Record as my database option. This is my first time of using Active Record with Sinatra.

I have successfully created my table, but I am getting an error whenever I try to "rake db:migrate".

I have gone through likely issues I found on Stack overflow, but not getting any headway. Any help would be appreciated.

Error message for "rake db:migrate

rake aborted!
ActiveRecord::ConnectionNotEstablished: ActiveRecord::ConnectionNotEstablished

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Below is my Rakefile

require_relative './app/controllers/recipe_controller'
require 'sinatra/activerecord/rake'
task :console do
    Pry.start
end

Below is my config/environment file

require 'bundler'
require 'bundler/setup'
Bundler.require

ActiveRecord::Base.establish_connection(
  adapter: 'sqlite3',
  database: 'db/development.sqlite'
)

require './app/controllers/recipe_controller'

Below is config.ru file

require "sinatra"

require './app/controllers/recipe_controller'

run RecipeController

my create_recipes file

class CreateRecipes < ActiveRecord::Migration[7.0]
  def change
    create_table :recipes do |t|
      t.string :name
      t.text :description
      t.boolean :completed

      t.timestamps
  end
end

jeudi 13 octobre 2022

Image Gets Uploaded While env is set to Amazon S3 but shows YAML error when env set to local

YAML syntax error occurred while parsing /app/config/storage.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Error: (): did not find expected tag URI while parsing a tag at line 16 column 11

this is occurring while uploading image from Spree Commerce Admin Panel

mercredi 12 octobre 2022

How to validate presence of attributes in json objects in an array in rails 3?

I am supposed to create an API for storing record that comes from json object. Basically the Json object contains an array of json objects that need to be validated before saving to db. e.g

    { 
      "request": [ 
                {
                 "country_id": 123,
                 "state_id" : 43,
                 "active": true,
                },
                {
                 "country_id": 234,
                 "state_id": 56,
                 "active": false,
                }
               ]
       }

So these objects needs to be inserted in Profile model in bulk which has country_id, state_id and active as attributes. So I want to validate the presence of attributes in the JSON objects in the Array while looping through them. If gets validated insert in the db otherwise return validation error in response.

    array = params[:request]
    array.each do |obj|
       Profile.new(obj)
       Profile.save!
    end
                  
           

mardi 11 octobre 2022

ActionController::RoutingError (uninitialized constant ContactsController Object.const_get(camel_cased_word) Did you mean? ContactController

I am a newbie to web development and currently learning. I have a problem: when I click the submit button, it doesn't push the values into the Hash and shows me the following error message:

Started POST "/contacts" for 49.37.171.198 at 2022-10-11 13:38:17 +0000
Cannot render console from 49.37.171.198! Allowed networks: 127.0.0.0/127.255.255.255, ::1
  ActiveRecord::SchemaMigration Pluck (0.5ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  
ActionController::RoutingError (uninitialized constant ContactsController

      Object.const_get(camel_cased_word)
            ^^^^^^^^^^
Did you mean?  ContactController

            raise MissingController.new(error.message, error.name)
            ^^^^^):

here in this controller.rb file when i create a global variable with the Contact.new (which i think is the class from Model files) ,it dosen't create a hash with values after clicking the submit button and gives me the above errors

contacts_controller.rb

class ContactsController < ApplicationController
  
  def new
    @Contact = Contact.new
  end
  
  def Create
    @Contact = Contact.new(contact_params)
    
    if @Contact.save
      flash[:success] = "Message Successfully Sent"
      redirect_to new_contact_path
      
    else
      flash[:danger] = @Contact.errors.full_messages.join(", ")
      redirect_to new_contact_path
      
    end
  end
    
    private
      def contact_params
        params.require(:contact).permit(:Name, :Email, :Comments) 
      end
      
end

new.html.erb

<div class="container">
  <div class='row'>
    <h3 class="container text-center contact-head3">Contact Us.</h3>
        
        
    <div class='col-md-5 col-md-offset-5'>

      <div class='well'>
        
        <%= form_for @Contact do |f| %>
                        
          <div class='form-group'>
            <%= f.label :Name %>
            <%= f.text_field :Name , class:'form-control' %>
          </div>
                    
          <div class='form-group'>
            <%= f.label :Email %>
            <%= f.text_field :Email, class:'form-control' %>
          </div>
                    
          <div class='form-group'>
            <%= f.label :Comments %>
            <%= f.text_area :Comments, class:'form-control' %>
          </div>
                        
          <div>
            <%= f.submit 'Submit', class:'btn btn-default' %>
          </div>
                    
        <% end %>
      </div>
    </div>
</div>
    

</div>

application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Sapna Xerox</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet">
    
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>

  <body>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
    <div class = "outer-navbar-sides">
      <div class='container'>
        <ul class=" nav nav-tabs">
    
          <li><%= link_to "Home",root_path%></li>
          <li><%= link_to "About",about_path%></li>
          <li><%= link_to "Contact",new_contact_path %></li>
    
        </ul>
      </div>
    </div>
    
    <div class="padding-fixer-of-container">
      <main class="container mx-auto mt-28 px-5 flex header">
    </div>
    
    <div class='container'>
      <% flash.each do |type,msg| %>
        <%= content_tag :div, msg, class:"alert alert #{type}" %>
      <% end %>
    </div>
    
      
      <%= yield %>
    </main>
  </body>
</html>

Contact.rb

    class Contact < ActiveRecord::Base
      
    end

routes.rb

Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"
  
  root to: 'pages#home'
  get '/about', to: 'pages#about'
  resources :contacts, only: [:create]
  get 'contact-us', to: 'contact#new', as: 'new_contact'
end

dimanche 2 octobre 2022

how to return a value in a call back function?

I tried the following two methods. Only the method 2 can return the region value if I passed output as an argument and reassigned the output to the region variable. How can I make the method 1 returning the region value? It finds the region value but at the end, the output returns an empty array in method one. How can I make the method one return a region value instead of an empty array? method 1

class abc

get_ticket_comment(){

  region=get_region(tickets)
  
}

get_region(tickets){
  output=[]
  tickets.each do |ticket|
    if ticket.start_with? "a" and ticket.loction.nil?
      get_region(ticket)
      if !output.empty?()
        return
      end
    elsif ticket.start_with? "a"
      if ticket.location
        output<< ticket.location
        break
    end
  end
return output
}

end

method 2

class abc

get_ticket_comment(){
  output=[]
  region=get_region(tickets, output)
  region=output
}

get_region(tickets,output){
  tickets.each do |ticket|
    if ticket.start_with? "a" and ticket.loction.nil?
      get_region(ticket,output)
      if !output.empty?()
        return
      end
    elsif ticket.start_with? "a"
      if ticket.location
        output<< ticket.location
        break
    end
  end
}
end