jeudi 29 décembre 2022

Failure: Expected 0 to be >=1

I got such output during bundle exec rake test: Someone please explain why am I not getting the intended rails test result(

F

Failure:
StaticPagesControllerTest#test_should_get_home [/Users/ivansharov/RubymineProjects/sample_app/test/controllers/static_pages_controller_test.rb:11]:
<Home | > expected but was
<Home | Ruby on Rails Tutorial Sample App>..
Expected 0 to be >= 1.


rails test test/controllers/static_pages_controller_test.rb:8

F

Failure:
StaticPagesControllerTest#test_shoud_get_contact [/Users/ivansharov/RubymineProjects/sample_app/test/controllers/static_pages_controller_test.rb:29]:
<Contact | > expected but was
<Contact | Ruby on Rails Tutorial Sample App>..
Expected 0 to be >= 1.


rails test test/controllers/static_pages_controller_test.rb:26

F

Failure:
StaticPagesControllerTest#test_shoud_get_about [/Users/ivansharov/RubymineProjects/sample_app/test/controllers/static_pages_controller_test.rb:23]:
<About | > expected but was
<About |  | Ruby on Rails Tutorial Sample App>..
Expected 0 to be >= 1.


rails test test/controllers/static_pages_controller_test.rb:20

F

Failure:
StaticPagesControllerTest#test_should_get_help [/Users/ivansharov/RubymineProjects/sample_app/test/controllers/static_pages_controller_test.rb:17]:
<Help | > expected but was
<Help | Ruby on Rails Tutorial Sample App>..
Expected 0 to be >= 1.

It is my static_pages_controller_test.rb file:


require "test_helper"

def setup @base_title = "Ruby on Rails Tutorial Sample App" end

class StaticPagesControllerTest < ActionDispatch::IntegrationTest test "should get home" do get static_pages_home_url assert_response :success assert_select "title", "Home | #{@base_title}" end

test "should get help" do get static_pages_help_url assert_response :success assert_select "title", "Help | #{@base_title}" end

test "shoud get about" do get static_pages_about_url assert_response :success assert_select "title", "About | #{@base_title}" end

test "shoud get contact" do get static_pages_contact_url assert_response :success assert_select "title","Contact | #{@base_title}" end end

lundi 26 décembre 2022

Is there a python difflib.get_close_matches("targetString", array) equivalent in Ruby?

Is there a method in Ruby similar to Python's difflib.get_close_matches("<target_string>", "[<array_of_strings>]") method?

multiple operation in array to create and update record in ruby

I have one use case when i am inserting an object and again updating it in another flow into database. First time, I am storing an 'array of object' into an object. Below is the structure of array of object.

request = [{"question"=>"sample question1", "answer"=>"sample answer1"}, {"question"=>"sample question2", "answer"=>"sample answer2"}]

In another flow, I want to update the same object with updated value.

request = [{"question"=>"sample question1", "answer"=>"updated answer1"}, {"question"=>"sample question2", "answer"=>"updated answer2"}, {"question"=>"sample question1", "answer"=>"sample answer3"}]

Now can someone please suggest me the optimal solution to perform this operation in ruby.

Overall structure should be like this: While inserting first time:

details = [#Details _id:3748y92eh2, name:"random name", email:"xyz@test.com", q&a:[[{"question"=>"sample question1", "answer"=>"sample answer1"},{"question"=>"sample question2", "answer"=>"sample answer2"}]]]

After update:

details = [#Details _id:3748y92eh2, name:"random name", email:"xyz@test.com", q&a:[[{"question"=>"sample question1", "answer"=>"updated answer1"},{"question"=>"sample question2", "answer"=>"updated answer2"}, {"question"=>"sample question1", "answer"=>"sample answer3"}]]]

Since I am new to ruby, can someone please suggest here.

dimanche 25 décembre 2022

Rails inherit class shared attributes on build

assuming i have two models human and male, they both have similar attributes but not all the attributes, for example:

class Human < ApplicationRecord
  has_many :males
  
  validates :name, presence: true
  validates :age, presence: true
  validates :date_of_birth, presence: true
  validates :identity, presence: true
end


class Male < ApplicationRecord
  belongs_to :human
  
  validates :name, presence: true
  validates :age, presence: true
end

now what i want to do is when i use human.males.build i want the new male instance to inherit the shared attributes like name and age instead of using this behavior human.males.build({attributes})

vendredi 23 décembre 2022

How can I fix Rails browser application owner error?

I started to learn Ruby on Rails and I am facing a problem with my Chrome browser.

I am starting my server with Command Prompt.

My Ruby version is: 2.7

My Rails version is: 7.0

When it comes to bug or a error it is not showing me in browser, I just get message: We're sorry, but something went wrong. If you are the application owner check the logs for more information.

How can I fix this, so I can see error on my browser.

I tried and looking only for solutions, but unsuccessfully.

mardi 20 décembre 2022

Facing errors in running the application of ruby

Im new to ruby and when try run a application, Im facing the below error

Gemfile:

source 'https://rubygems.org'
gem 'rails'
gem 'mysql2'
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'haml'
gem 'nifty-utils'
gem 'nilify_blanks'
gem 'authie'
gem 'kaminari'
gem 'chronic'
gem 'dynamic_form'
gem 'activevalidators'
gem 'bcrypt', '3.1.7'
gem 'rails_env_config'
gem 'chronic_duration'
gem 'datey'
gem 'nifty-attachments'
gem 'puma'
gem 'moonrope'
gem 'florrick'
gem 'delayed_job_active_record'
gem 'foreman'
gem 'redcarpet', '3.5.1'
gem 'premailer'

group :development, :test do
  gem 'byebug'
  gem 'web-console'
  gem 'annotate'
  gem 'pry-rails'
end

Error:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Development/status/vendor/bundle/ruby/2.6.0/gems/racc-1.6.1/ext/racc/cparse
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby -I /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0 -r
./siteconf20221220-32692-ivgdf1.rb extconf.rb
checking for rb_block_call()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

while running the below command bundle --full-index

Error: Missing target element || Stimulus 1.1.1 Rails 6

I have this error 'Error: Missing target element' in console when i try to select one target.

The main idea here is to iterate through an array of web_servers so I create one controller per instance and select one target per controller (the value is_available will change continuously, and I want to use action cable to monitor it).

My stimulus controller:

import { Controller } from "stimulus";
import consumer from "channels/consumer";

export default class extends Controller {
  static targets = ["status"];

  connect() {
    console.log('Will create subscription to: channel: "ScanServersStatusChannel" web_server_id: ' + this.data.get('id'));

    this.channel = consumer.subscriptions.create({ channel: 'ScanServersStatusChannel', web_server_id: this.data.get('id') }, {
      connected: this._cableConnected.bind(this),
      disconnected: this._cableDisconnected.bind(this),
      received: this._cableReceived.bind(this),
    });
  }

  _cableConnected() {
    // Called when the subscription is ready for use on the server
    console.log('_cableConnected');
    console.log(this.statusTarget);

  }

  _cableDisconnected() {
    // Called when the subscription has been terminated by the server
    console.log('_cableDisconnected');
  }

  _cableReceived(data) {
    // Called when incoming data from websocket
    const element = this.statusTarget
    element.innerHTML = data
  }
}

My view:

<% @web_servers.each do |web_server, index| %>
  <div data-controller="serverstatus" data-serverstatus-id="<%= web_server.id %>">
      <tbody class="accordion">
        <tr>
          <td id="web-server-id"><%= web_server.id %></td>
          <td><%= web_server.port_number %></td>
          <td><%= web_server.address %></td>
          <div data-target="serverstatus.status">
            <td><%= render 'admin/dashboards/web_servers/web_server_status', web_server: web_server%></td>
          </div>
        </tr>
      </tbody>
  </div>
<% end %>

Inside the partial:

<span ><%= web_server.is_available ? 'Disponible' : 'Non disponible' %></span>

lundi 19 décembre 2022

How to make routes for this URL?

GET /bids?countries=us,uk&categories=finance,sports&channels=ca,ga

And the expected response is:

{
  "bids": [
    { 'country': 'us', 'category': 'finance', 'channel': 'ca', 'amount': 4.0 },
    { 'country': 'us', 'category': 'finance', 'channel': '2ga', 'amount': 2.0 },
    { 'country': 'us', 'category': 'sports', 'channel': 'ca', 'amount': 2.0 },
    { 'country': 'us', 'category': 'sports', 'channel': 'ga', 'amount': 2.0 },
    { 'country': 'uk', 'category': 'finance', 'channel': 'ca', 'amount': 1.0 },
    { 'country': 'uk', 'category': 'finance', 'channel': 'ga', 'amount': 1.0 },
    { 'country': 'uk', 'category': 'sports', 'channel': 'ca', 'amount': 3.0 },
    { 'country': 'uk', 'category': 'sports', 'channel': 'ga', 'amount': 3.0 }
  ]
}

How to make routes for this url please help me out - any more experienced people know what I am doing for making routes ?. thanks in advance.

dimanche 18 décembre 2022

Faild to install nokogiri 1.8.2 with native extensions

NameError: uninitialized constant Gem::Command

      Gem::Command.build_args
         ^^^^^^^^^
An error occurred while installing nokogiri (1.8.2), and Bundler cannot continue.
Make sure that `gem install nokogiri -v '1.8.2'` succeeds before bundling.

I've tried:

gem install nokogiri -v '1.8.2'
sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev
apt-get install openssl ruby-openssl libssl-dev
gem install nokogiri -- --use-system-libraries
gem install nokogiri -- --with-xml2-config=/path/to/xml2-config
gem install nokogiri -- --with-xslt-config=/path/to/xslt-config
bundle config build.nokogiri --use-system-libraries (command that caused this new error. The error before was another, but in essence it was an error when installing nokogiri)

Current OS: Ubuntu 22.04.1 LTS

Ruby version: ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [x86_64-linux] (installed using RVM)

Rails version: Rails 7.0.4

vendredi 16 décembre 2022

Ruby on Rails Enum fetch

I have a enum and two Constant

  enum status: { draft: 0, published: 1 }

  I_CODE = 23
  J_CODE = 24

I have a method in that I have to check status is draft then in database I have to save value 23 and if status is published I have to save 24 in database. when I am trying to compare like status == draft? then it is not working.

  def status=(status)
   self[:status] =
   if status.blank?
     nil
   elsif status == 0
     I_CODE
   elsif status == 1
     M_CODE
   end
 end

But for showing in UI I want to show if status == draft then it should show draft.

def status
  if status == 0
    Draft
  elsif status == 1
    Published
  else
    "----"
  end
end

Could someone please help me.

mercredi 14 décembre 2022

Problem with migration when i am implementing paper clip

enter image description here

class AddAttachmentAvatarToLists < ActiveRecord::Migration[7.0]
    def change
    create_table :lists do |t|
      t.attachment :avatar
      t.timestamps
    end
  end
end

The error is as follows and I cannot figure out how to fix it - any more experienced people know what I am doing wrong?

mardi 13 décembre 2022

Using ActiveRecord to query count() over()

I want to limit the SQL query result set while also knowing how many possible rows match. I found that (with Postgresql), I could write

SELECT *,count(*) over() as total FROM ... WHERE ... LIMIT 5

which will return a max of 5 rows, with a column called total which contains the total number of rows which match the query (it's the same value for all rows); this, to avoid multiple queries.

How can represent this as an ActiveRecord query? While I can pass the select clause to .select, but the "count(*) over()" field is ignored. I had to resort to exec_query and specify then entire select string.

(Rails)Where should i define method that can use in Rspec and Controller?

I'm making method that can used in Rspec test and Controllers. But i don't know where to store it.

Here are options that i have thought.

  1. application_helper -> but this file is used for method which used in applicaion controller.

  2. spec_helper.rb

  3. rails_helper.rb -> these two file is for rspec test

where should i store it?

I read this article but i'm not using models.

How to make a custom method that can be used anywhere in rails app

Now i had stored it at application_helper.rb, and call as

ApplicationController.helpers.custom_method

Is this right practice?

vendredi 9 décembre 2022

Can i use factorybot before whole rspec test?

I'm now using factory bot for my Rspec test. But my code calls factory bot's create method before each test like :

before(:each) do
  create(:user)
  ...
end

I have over 10 controllers, so it took lot's of time And i should copy that before block to each file when i make new Rspec test.

Can i make that code dry, such as "run factory bot's create method once before whole Rspec test starts"?

I think it is very efficient for save running test's time.

lundi 5 décembre 2022

Why can't I install ruby 3.1.2 in linux?

I tried:

if ! command -v ruby &> /dev/null
then
    # - proverbot's version
    # First, install Ruby, as that is for some reason required to build
    # the "system" project
#    git clone https://github.com/rbenv/ruby-build.git ~/ruby-build
#    mkdir -p ~/.local
#    PREFIX=~/.local ./ruby-build/install.sh
#    ~/.local/ruby-build 3.1.2 ~/.local/

    # - u-pycoq's version
#    sudo apt-get install ruby-full
    sudo apt-get install rbenv
    rbenv init
    eval "$(rbenv init - bash)"
    echo 'eval "$(rbenv init - bash)"' >> ~/.bashrc

    sudo apt-get install ruby-build
#    ruby-build 3.1.2
    rbenv install 3.1.2

    rbenv global 3.1.2
    ruby -v

else
    echo "Error: failed to install ruby"
fi

but I get my ruby build is not up to date perhaps but when I install it -- it is up to date. Therefore, why is the proverbot's attempt 3.1.2 if it doesn't exist?

inspired from: https://superuser.com/questions/340490/how-to-install-and-use-different-versions-of-ruby

dimanche 4 décembre 2022

ActionController::RoutingError (No route matches "/welcome/admin_dashboard"):

I am trying to setup VirtualX Assessment Software that I downloaded online. Here is the link where I got it: https://virtualx.sourceforge.net/download.html

I managed to make it run where I was able to load its webpage but there are still some functions where I'm getting an error.

Here, I'm trying to approve a test account that registered to the platform: enter image description here

When I hit approve, here is the error that I'm getting: enter image description here

Here is the content of routes.db

Virtualx::Application.routes.draw do
    
  get "errors/not_found"  
    
  get "subcategory/index"
  get "subcategory/list"
  get "subcategory/show"
  post "subcategory/save"
  post "subcategory/update"
  get "subcategory/edit"
  get "subcategory/new"
  get "subcategory/destroy"
  post "subcategory/destroy"  
  
  
  #resources :article
  get "article/index"
  get "article/show"
  get "article/list"
  get "article/comment"
  post "article/comment"
  get "article/new"
  post "article/save"
  get "article/edit"
  post "article/update"
  get "article/news"
  get "article/destroy"
  post "article/destroy"
    get "article/delete"
  post "article/delete"
  match '/getBlogcategory' => 'article#getBlogcategory'
  match '/thumbsUp' => 'article#thumbsUp'
  match '/thumbsDown' => 'article#thumbsDown'
  match '/delete_comment' => 'article#delete_comment'
  
  get "blog_category/index"
  get "blog_category/list"
  get "blog_category/show"
  post "blog_category/save"
  post "blog_category/update"
  get "blog_category/edit"
  get "blog_category/destroy"
  post "blog_category/destroy"
  get "blog_category/new"
  match '/subcategory' => 'blog_category#subcategory'
  match '/subcategory_article' => 'blog_category#subcategory_article' 
  match '/blog' => 'blog_category#blog' 
  match '/categoryArticle' => 'blog_category#categoryArticle'

  
  
  resources :users do
   get :autocomplete_user_name, :on => :collection
  end
  
  resources :folders
  get "folders/index"
  get "folders/new"
  get "folders/create"
  post "folders/create"
  get "assets/destroy"
  post "assets/destroy"  
  match "browse/:folder_id" => "folders#browse", :as => "browse"  
  match "browse/:folder_id/new_folder" => "folders#new", :as => "new_sub_folder"    
  match "browse/:folder_id/new_file" => "assets#new", :as => "new_sub_file"
  match "browse/:folder_id/rename" => "folders#edit", :as => "rename_folder"
  match '/getName' => 'folders#getName'
  match '/unshareFolder' => 'folders#unshareFolder'
  
  resources :assets 
  get "assets/index"
  get "assets/new"
  get "assets/create"
  post "assets/create"
  get "assets/destroy"
  post "assets/destroy"
match "assets/get/:id" => "assets#get", :as => "download"  
  match "assets/share" => "assets#share"
  match "assets/unshare" => "assets#unshare"
  match '/lock' => 'assets#lock'
  match '/unlock' => 'assets#unlock'  
  
  
  
  
resources :aboutus
resources :clientinfo
  resources :images 

  #get "images/index"
  #get "images/new"
  match '/view_aboutus' => 'home#view_aboutus'
  match '/view_clients' => 'home#view_clients'
  match '/view_features' => 'home#view_features'
  match '/view_modules' => 'home#view_modules'
  match '/view_contactus' => 'home#view_contactus'
  
  match '/deleteUsersubject' => 'users#deleteUsersubject'

match '/clientImage' => 'images#clientImage'
match '/createClientimage' => 'images#createClientimage'

  get "/questions/question_type_listing"
  post "/questions/new"
  resources :questions do
        member do
          get "delete_option"
      post "delete_option"
                get "delete_match_option"
      post "delete_match_option"
                      get "delete_matrix_row"
      post "delete_matrix_row"
                      get "delete_matrix_column"
      post "delete_matrix_column"
      get "delete_hrcl_option"
      post "delete_hrcl_option"
      
            get "saveImage"
      post "saveImage"
      
    end
  end
    #post "questions/publish_unpublish"
  #get "questions/publish_unpublish"
  match '/publish_unpublish' => 'questions#publish_unpublish'
  match '/unpublish' => 'questions#unpublish'
  match '/share' => 'questions#share' 

  match '/saveImage' => 'questions#saveImage'
   match '/sharewithCategory' => 'questions#sharewithCategory'
  match'/checkMark' => 'questions#checkMark'
   match'/viewQuestion' => 'questions#viewQuestion'
   
  get "subjects/add_subject_category"
  resources :subjects 
  
  post "subjects/cs"
  
  resources :categories
  resources :category_titles
  resources :emails  
    
  post "attend_exams/confirm_exam"
  get "attend_exams/confirm_exam"
  post "attend_exams/reject_exam"
  get "attend_exams/reject_exam"
  resources :attend_exams
  get "attend_exams/index"
  match '/examination' => 'attend_exams#examination'
  match '/instruction' => 'attend_exams#instruction'
  match '/evaluation' => 'attend_exams#evaluation'
  match '/evaluation' => 'attend_exams#ramdomizeQuestions'
   match '/examComplete' => 'attend_exams#examComplete'
   match '/calculateScore' => 'attend_exams#calculateScore'
   match '/windowClose' => 'attend_exams#windowClose'
   
   
   match 'welcome/examinee_dashboard' => 'welcome#examinee_dashboard'
  #get "exams/attend_exam"
  #post "exams/attend_exam"

  resources :exams 
  #  member do
      #get "exams/index"
  #  end
  #end
  match '/scheduleExam' => 'exams#scheduleExam'
  match '/selectQuestion' => 'exams#selectQuestion'
  match '/assignQustions' => 'exams#assignQustions'
  match '/selectExaminee' => 'exams#selectExaminee'
  match '/assignExaminees' => 'exams#assignExaminees'
  match '/previewExam' => 'exams#previewExam'
  match '/deleteExamQuestion' => 'exams#deleteExamQuestion'
  match '/deleteExamUser' => 'exams#deleteExamUser'
 match '/getMark' => 'exams#getMark'
 match '/assignExam' => 'exams#assignExam'
  match '/groupExam' => 'exams#groupExam'
 match '/updateMark' => 'exams#updateMark'
  match '/examtype' => 'exams#examtype'
   match '/create_examtype' => 'exams#create_examtype'
   match '/listExamtypes' => 'exams#listExamtypes'
  match '/editExamtype' => 'exams#editExamtype' 
   match '/deleteExamtype' => 'exams#deleteExamtype' 
   match '/updateExamtype' => 'exams#updateExamtype' 
match '/getExam' => 'exams#getExam'
 match '/showEvaluationtype' => 'exams#showEvaluationtype'
 match '/hideEvaluationtype' => 'exams#hideEvaluationtype'
 match '/evaluate' => 'exams#evaluate'
 match '/getExamQuestions' => 'exams#getExamQuestions'
 match '/manualEvaluation' => 'exams#manualEvaluation'
 match '/finishEvaluation' => 'exams#finishEvaluation'
 match '/getCategoryexams' => 'exams#getCategoryexams'
 match '/assignEvaluator' => 'exams#assignEvaluator'
  match '/getEvaluator' => 'exams#getEvaluator'
  match '/evaluator' => 'exams#evaluator'
  match '/delete_evaluator' => 'exams#delete_evaluator' 
  
 match '/completedExams' => 'attend_exams#completedExams'
 match '/pendingExams' => 'attend_exams#pendingExams'
 
 
  
  match '/updateCategory' => 'category_titles#updateCategory'
  match '/deleteCategory' => 'category_titles#deleteCategory'
  
  get "settings/index"
  post "settings/update"
  
  get "feedback/index"
  match '/assign' => 'feedback#assign'
  match '/unassign' => 'feedback#unassign'
  match '/viewFeedback' => 'feedback#viewFeedback'
  match '/submitFeedback' => 'feedback#submitFeedback'
  match '/viewfeedbackResponse' => 'feedback#viewfeedbackResponse'
  match '/feedbackResponse' => 'feedback#feedbackResponse'
    

  get "reports/index"
  
  get "results/index"
  match '/usersResult' => 'results#usersResult'
  match '/resultIndex' => 'results#index'
  match '/viewUserResult' => 'results#viewUserResult'
  match '/groupResult' => 'results#groupResult'
  match '/examsResult' => 'results#examsResult'
  match '/viewExamResult' => 'results#viewExamResult'
  match '/departmentResult' => 'results#departmentResult'
  match '/viewDepartmentResult' => 'results#viewDepartmentResult'
  
  #get "examination/index"
  
 # get "reports/generateDepartmentReport"
  
  match '/userReport' => 'reports#userReport'
  match '/viewuserReport' => 'reports#viewuserReport'
 match '/examReport' => 'reports#examReport'
match '/viewexamReport' => 'reports#viewexamReport'
match '/generateUser' => 'reports#generateUser'
match '/userSubjectwise' => 'reports#userSubjectwise'
match '/generateExamReport' => 'reports#generateExamReport'
match '/departmentReport' => 'reports#departmentReport'
match '/viewDepartmentReport' => 'reports#viewDepartmentReport'
match '/generateDepartmentReport' => 'reports#generateDepartmentReport'
match '/viewDepartmentReportgraph' => 'reports#viewDepartmentReportgraph'
match '/highLevel' => 'reports#highLevel'
match '/reportYear' => 'reports#reportYear'
match '/overall' => 'reports#overall'
match '/specificDepartment' => 'reports#specificDepartment'
match '/departmentDetailed' => 'reports#departmentDetailed'
match '/semesterDetailed' => 'reports#semesterDetailed'
match '/pass_fail' => 'reports#pass_fail'
match '/generatePassfail' => 'reports#generatePassfail'
match '/fetchExam' => 'reports#fetchExam'

match '/listCategories' => 'categories#listCategories'
match '/delete_category' => 'categories#delete_category'



  get "questions/index"

  get "subjects/index"


 # resources :settings
  resources :temporary_examinee
  #get "temporary_examinee/new"
  #get "temporary_examinee/create"
  #post "temporary_examinee/create"


  #get "user_registration/new"
  resources :user_registration

  
  #resources :welcome
  get "welcome/index"
  get "welcome/admin_dashboard"
  get "welcome/examiner_dashboard"
  get "welcome/qsetter_dashboard"
  get "welcome/examinee_dashboard"
  post "welcome/confirm_registration"
  get "welcome/confirm_registration"
  post "welcome/reject_registration"
  get "welcome/reject_registration"
  get "welcome/user_management"
  get "welcome/workflow"
  
  get "passwords/new"

  #get "passwords/forgot"
  match 'groupUser' => 'users#groupUser'
  match 'createGroup' => 'users#createGroup'
  get "user_sessions/new"

  get "users/new"
  get "users/generate_temporary_password"
  post "users/generate_temporary_password"
  match 'activate_inactivate' => 'users#activate_inactivate'
    match 'activate' => 'users#activate'
      match 'inactivate' => 'users#inactivate'
  #match 'users/tempexaminee' => 'users#new'

  resources :users 
  get "users/show"

  get "users/edit"
  
  
  get "home/index"

  get "user_sessions/new"
  resources :user_sessions
 
  match 'login' => "user_sessions#new",      :as => :login
  match 'logout' => "user_sessions#destroy", :as => :logout
    
  #get "password_resets/new"
  resources :password_resets do
    member do
      get 'confirmEmail'
      get 'setPassword'
      get 'savePassword'
      post 'savePassword'
      get 'verifyPassword'      
    end
  end
  get "password_resets/edit"


 # post "password_resets/edit"

  get    'verify/:id'       => 'user_verifications#index'
  
  # The priority is based upon order of creation:
  # first created -> highest priority.

  # Sample of regular route:
  #   match 'products/:id' => 'catalog#view'
  # Keep in mind you can assign values other than :controller and :action

  # Sample of named route:
  #   match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
  # This route can be invoked with purchase_url(:id => product.id)

  # Sample resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Sample resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Sample resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Sample resource route with more complex sub-resources
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', :on => :collection
  #     end
  #   end

  # Sample resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end

  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  # root :to => "welcome#index"
    root :to => 'home#index'
    resources :home
  # See how all your routes lay out with "rake routes"

  # This is a legacy wild controller route that's not recommended for RESTful applications.
  # Note: This route will make all actions in every controller accessible via GET requests.
  # match ':controller(/:action(/:id(.:format)))'
end

Here is the content of welcome_controller:

=begin
  welcome_controller.rb
  Description: Controller file for managing the Welcome page of the application
  Created on: October 11, 2010
  Last modified on: March 18, 2013
  Copyright 2013 PIT Solutions Pvt. Ltd. All Rights Reserved.
=end

class WelcomeController < ApplicationController
  filter_access_to :all
  #layout "home"
  layout :choose_layout

  def choose_layout
    if action_name == 'workflow'
      return 'workflow'
    else 
      return 'application'
   end
  end
  
  def index
  end

  def workflow
    
  end
  
  def admin_dashboard
    @setting = Setting.find(:first)
    @pageCollect = params[:pageLength].to_i
    if @pageCollect == 0
      @pagelength = 10
    else
      @pagelength = params[:pageLength].to_i
    end
    if params[:char]
      letter = params[:char]
      @letter = params[:char]
      @registered_examinees = User.where(["is_registered = ? and role_id = ? and is_temp_examinee = ? and name like '#{params[:char]}%'", 1,Examinee,0]).paginate(:page => params[:page], :per_page => @pagelength)
      @unapproved_examinees = User.where(["is_registered = ? and confirmed != ? and role_id = ? and is_temp_examinee = ? and name like '#{params[:char]}%'", 1,1,Examinee,0])
    else
      @registered_examinees = User.where(["is_registered = ?",1]).paginate(:page => params[:page], :per_page => @pagelength)
      @unapproved_examinees = User.where(["is_registered = ? and confirmed != ? and role_id = ? and is_temp_examinee = ? and name like '#{params[:char]}%'", 1,1,Examinee,0])
    end
  end
  
  def examiner_dashboard
    
  end
  
  def qsetter_dashboard
    
  end
  
  def examinee_dashboard
    
  end
  
  def confirm_registration
    @all_approved_users = params[:check_examinee]
    @all_approved_users.each do|approved|
      @user = User.find_by_id(approved.to_i)
      @user.update_attributes(:is_approved => 1)
      if (@user.is_approved == 0 and @user.confirmed == false) or (@user.is_approved == 1 and @user.confirmed == false) or (@user.is_approved == 2 and @user.confirmed == false)
       UserMailer.user_registration_email_confirmation(@user,$pwd).deliver
      end
    end
     flash[:success] = t('flash_success.email_verification')
      respond_to do |format|
        format.html { redirect_to :back }
         format.js
      end
  end
  
  def reject_registration
    @rejected_users = params[:check_examinee]
    @rejected_users.each do|rejected|
      @user = User.find_by_id(rejected.to_i)
      unless (@user.is_approved == 2 and @user.confirmed == false)
      @user.update_attributes(:confirmed => false,:is_approved => 2)
      UserMailer.examinee_registration_rejection(@user).deliver
      end
    end
     flash[:success] = t('flash_success.email_rejection')
      respond_to do |format|
        format.html { redirect_to :back }
         format.js
      end
    
  end
  
end

Here is the content of admin_dashboard:

<div id="flash_notice" style="display: none;"></div>

<h2><%= t('welcome.filter_examinees')%></h2>
<div class="formContainer">
    <table class="formTable" style="border:0px;">
        <tr>
            <td style="width:auto;" class="lettersort"><%= link_to t('general.all'), :action=>"admin_dashboard"%> | <% for char in 'A'..'Z' %>
            <%= link_to( "#{char}", :char=>char, :action=>"admin_dashboard")%>
            <%end%></td>

        </tr>
    </table>
</div>

<%if @setting.examineeApprove == 1%>
<div class="updateStatus">
    <%unless @registered_examinees.empty?%>
    <div class="qestionhead">
        <h3><%= t('welcome.reg_examinees')%></h3>   
        <%= render :partial=>"users/pageLinks"%>
    </div>
    <%end%>
    <%unless @letter == nil%>
    <%= hidden_field_tag "char",@letter%>
    <%else%>
    <%= hidden_field_tag "char"%>
    <%end%>
    <div id="examinee_activation">
        <%= render 'activation', :collection => @registered_examinees%>
    </div>
    <br>
</div>
<%else%>
<%= t('user.user_notfound')%>
<%end%>

<script type="text/javascript">

    $(document).ready(function() {

$(".pageNum").click(function(){
var data = {pageLength: this.id, char: $("#char").val()};
var url = "<%= url_for(welcome_admin_dashboard_path)%>
    ";
    $.get(url, data)

    $(".pageNum").live("click", function(){
    var url = "
<%= url_for(welcome_admin_dashboard_path)%>
    ";
    var target = url + "?pageLength=" + this.id + "&char=" + $("#char").val()
    $.getScript(target,$("#" + this.id).serialize(),function(data){
    });
    //$.getScript(this.href,+"?pageLength="+this.id);
    return false;
    });

    });

    $("#examinee_activation .pagination a").live("click", function(){

    var link = this.href
    var lastChar = link.substr(link.length - 1);
    if (lastChar == '#'){
    return false;
    }
    else{
    $.getScript(this.href);
    return false;
    }
    });

    });

</script>

Sorry for including everything. I am very new to this and I'm just trying to run something that was created by others. Any help to fix why I'm getting this error is greatly appreciated.

samedi 3 décembre 2022

Error while trying to install mysql in Ruby on rails

Ruby version - ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [x64-mingw-ucrt]

Rails Version - Rails 7.0.4

Command = gem install mysql2

I have already install mysql community version and placed libmysql.dll in C:\Ruby31-x64\bin

Error Details

Temporarily enhancing PATH for MSYS/MINGW... Using msys2 packages: mingw-w64-ucrt-x86_64-libmariadbclient Building native extensions. This could take a while... ERROR: Error installing mysql2: ERROR: Failed to build gem native extension.

current directory: C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/mysql2-0.5.4/ext/mysql2

C:/Ruby31-x64/bin/ruby.exe -I C:/Ruby31-x64/lib/ruby/3.1.0 extconf.rb checking for rb_absint_size()... yes checking for rb_absint_singlebit_p()... yes checking for rb_wait_for_single_fd()... yes checking for rb_enc_interned_str() in ruby.h... yes *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.

Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=C:/Ruby31-x64/bin/$(RUBY_BASE_NAME) --with-mysql-dir --without-mysql-dir --with-mysql-include --without-mysql-include=${mysql-dir}/include --with-mysql-lib --without-mysql-lib=${mysql-dir}/lib --with-mysql-config --without-mysql-config --with-mysqlclient-dir --without-mysqlclient-dir --with-mysqlclient-include --without-mysqlclient-include=${mysqlclient-dir}/include --with-mysqlclient-lib --without-mysqlclient-lib=${mysqlclient-dir}/lib --with-mysqlclientlib --without-mysqlclientlib C:/Ruby31-x64/lib/ruby/3.1.0/mkmf.rb:1083:in block in find_library': undefined method split' for nil:NilClass (NoMethodError)

paths = paths.flat_map {|path| path.split(File::PATH_SEPARATOR)}
                                   ^^^^^^
    from C:/Ruby31-x64/lib/ruby/3.1.0/mkmf.rb:1083:in `each'
    from C:/Ruby31-x64/lib/ruby/3.1.0/mkmf.rb:1083:in `flat_map'
    from C:/Ruby31-x64/lib/ruby/3.1.0/mkmf.rb:1083:in `find_library'
    from extconf.rb:103:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

C:/Ruby31-x64/lib/ruby/gems/3.1.0/extensions/x64-mingw-ucrt/3.1.0/mysql2-0.5.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/mysql2-0.5.4 for inspection. Results logged to C:/Ruby31-x64/lib/ruby/gems/3.1.0/extensions/x64-mingw-ucrt/3.1.0/mysql2-0.5.4/gem_make.out

vendredi 2 décembre 2022

Access value from a Netsuite hash, Enumerator

Hi I am trying to extract a value from a Netsuite hash inside custom fields, and some others, which typically look like this - `

"custbody_delivery_ticket_number"=>
 {
 "script_id"=>"custbody_delivery_ticket_number", 
 "internal_id"=>"2701", 
 "type"=>"platformCore:DateCustomFieldRef", 
 "attributes"=> {
 "value"=>"123abc"
 }

}` and want the value of it inside of attributes.

Have tried many different ways, but one in particular -

 delivery_ticket_number: "#{netsuite_sales_orders.custom_field_list.custom_fields.select['custbody_nef_meter_ticket_number']['attributes']['value']}", 

throws error for class Enumerator, NoMethodError: undefined method `[]' for #Enumerator:0x00005589ec778730 which indicates may be getting close, but doing something wrong.

If anyone has any idea how to get values from these kind of hashes?

(Am told by the system admin that it is the correct custbody identifier)

Many Thanks

jeudi 1 décembre 2022

how to add extra value to query in ruby

hello i have query to fill list box with this query how i can add an static value to select all clients

tipo = $evm.root['dialog_param_type']
option = $evm.root['dialog_param_action']
dialog_field = $evm.object
if tipo == "ALL"
  puts option
  dialog_field['read_only'] = "true"
  $evm.object['values'] = {1 => "-- Please select an option from above --"}
else
  puts option
  dialog_field['read_only'] = "false"
  values= {}
  customer_list= {}

  get_query($evm.object.decrypt('query')).each do |$evm.object['values'] = {1 => "-- Please select an option from above --"}|item|
    customer_list["#{item['customer_id']}", Customer id: *] = item['customer_name'].to_s
  end
  dialog_field['values'] = customer_list
end

it fills it with clients on my db; so i wanted to add an option to select them all like aditional value values= {ALL=> *}}

mardi 29 novembre 2022

Can't make code_ownership and code_teams gems to work

The gems code_teams, code_ownership should allow one to tag files/whole folders by team name but after adding them to my project, running bundle install etc, I still encounter the same error

Passed `nil` into T.must

sample team file (placed in config/teams as advised) is as following

name: Smurfs
owned_globs:
  - folder/filename1.rb

The code where I try to use the info is :

x = CodeOwnership.for_backtrace(e.backtrace)

dimanche 20 novembre 2022

Rails call custom validation before .new or .create

I make objects in controller's loop.

I need to check pet_name array before loop starts. (because i got undefined method 'each' for nil:NilClass when params[:pet_name].each do |pid|) runs)

But my validation always called after User.new or User.create. I want to change to validate as when i push submit button and check validation, and redirects back when pet_name array is nil. Ho can i change my code?

Controller

  def create
    user_name = params[:user_name]
    
    params[:pet_name].each do |pid|
      @user = User.new
      @user.name = user_name
      @user.pet_name = pid
      render :new unless @user.save
    end
    redirect_to users_path
  end

User.rb

class User < ApplicationRecord
  has_many :pet

  validates :name, presence: true
  validates :pet_name, presence: true
  validate :check_pet
  def check_pet
    if pet_name.nil?
      errors.add(:pet_name, 'at least one pet id')
    end
  end
end

Prams structure

  { name: 'blabla', pet_name: ['blabla', 'blablabla', 'bla'] }

samedi 19 novembre 2022

Obstacle with Ruby Rails Authentication

I am a brand new Ruby on Rails User

When I enter localhost:3000 ,

I get an error reading

Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development You have 2 pending migrations: 20221119205559_add_devise_to_users.rb 20221119211811_drop_users_table.rb

# Raises <tt>ActiveRecord::PendingMigrationError</tt> error if any migrations are pending.
      def check_pending!(connection = Base.connection)
        raise ActiveRecord::PendingMigrationError if connection.migration_context.needs_migration?
      end

      def load_schema_if_pending!

In a nutshell, it was working before but I attempted to create a a basic authentication page(which was also working) , but for some reason when I clicked sign up I received an error also.

Thank you for any tips on how to fix this!

I have tried to

rake db:drop
rake db:create
rake db:migrate

Editing the migrate file with: 

 edit your migration file

class DropUsersTable < ActiveRecord::Migration
  def change
    drop_table :users
  end
end

Then doing rake db:migrate

Also, I have run :


rails generate devise:install rails generate devise User bundle exec rake db:migrate



jeudi 17 novembre 2022

Creating array value in Rspec with let() method

how can i make array value in rspec test?

If I make array like this (in SAMPLE_spec.rb file), ->>

let(:fruit) { [name:  ‘apple’, color: ‘red’] }

fruit.length --->> this becomes error

fruit[0].length --->>this works well

i want to make array and use like fruit.length. how can i change my code?

mercredi 16 novembre 2022

Write a program which gets a number from a user and identify whether it is an Integer or a Float in ruby

I am trying this :

print " Enter Value " num = gets.chomp

also tried .kind_of? but didn't work

if num.is_a? Float
print " Number is in float "

also tried .kind_of? but didn't work

else num.is_a? Integer
print " Number is in integer "

end

dimanche 13 novembre 2022

Cannot Send Email From Send Grid With Attachment 300 kb

I try to send email using sendgrid with attachment file (pdf). Its working good for attachment less than 250 kb. But when I try to send email with attachment file with size above 250 kb, I get error from send grid said, 552 5.2.3 your message exceeded google's size limit, but the attachment file only 300 kb. Can someone help me with this issue? thank you in advance.

jeudi 10 novembre 2022

2 arrays insert via (column) double dimension array ruby (short method)

From this initialize array:

x = []
y = [1,2,3,4,5]
z = ["a", "b", "c", "d", "e"]

I want x result to be like this:

=> [[1,"a"], [2,"b"], [3,"c"], [4,"d"], [5,"e"]]

Is there any short method to do this without using nested loop?

Can we call ASP.Net page load function from Rails application?

I'm facing an issue while calling the ASP.Net function from Rails. First I want to know that Is it possible to call the ASP.Net function from Rails?

I tried to call it but facing <Net::HTTPUnauthorized 401 Unauthorized readbody=true> error message

I also passed the username and password with it.

Thank you.

lundi 7 novembre 2022

OPTIMIZE QUERY ON RAILS - POSTGRESQL

I have 3 scopes: 1 - lists the promotions in progress. 2 - sort out of stock last 3 - list the promotions that are not in progress.

Is it possible to combine everything in a single scope? It would be: List the promotions in progress, in order of stock from highest to lowest, and then the promotions that are not in progress.

I tried, but I couldn't.

scope :in_progress, -> { start_and_end_dates.in_weeks.between_hours }
    
scope :without_stock_last, lambda {
  select('promotions.*, (CASE WHEN offers.current_inventory > 0 THEN 1 ELSE 0 END) AS "is_available"')
   .order('is_available DESC')
   .group('promotions.id, offers.current_inventory, offers.created_at')
}
    
scope :not_progress, lambda {
  promotions_in_progress = Promotion.in_progress.pluck(:id).join(",")
  Promotion.with_estabilishment.select("promotions.*, (CASE WHEN promotions.id NOT IN (#{promotions_in_progress}) THEN 0 END) AS is_unavailable")
  .order('is_unavailable DESC')
}

mercredi 2 novembre 2022

Unpermitted parameter: :image. (carrierwave )

i am creating a form where you can upload the image file, but whenever i submit the form, it dosent permit the image and in the terminal it shows "Unpermitted parameter: :image. Context: { controller: InstrumentsController, action: update, request: #ActionDispatch::Request:0x00007f1955b24b50, params: {"_me................."

also if i check using the rails console if the image is being uploaded or not by typing the Instrument.all (Instrument is a table in database), it shows that it is nil,

i have permitted the :image in params

instruments_controller.rb

class InstrumentsController < ApplicationController
  before_action :set_instrument, only: %i[ show edit update destroy ]
  before_action :authenticate_user!, except: [:index, :show]

  # GET /instruments or /instruments.json
  def index
    @instruments = Instrument.all.order("created_at desc")
  end

  # GET /instruments/1 or /instruments/1.json
  def show
  end

  # GET /instruments/new
  def new
    @instrument = current_user.instruments.build
  end

  # GET /instruments/1/edit
  def edit
  end

  # POST /instruments or /instruments.json
  def create
    @instrument = current_user.instruments.build(instrument_params)

    respond_to do |format|
      if @instrument.save
        format.html { redirect_to instrument_url(@instrument), notice: "Instrument was successfully created." }
        format.json { render :show, status: :created, location: @instrument }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @instrument.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /instruments/1 or /instruments/1.json
  def update
    respond_to do |format|
      if @instrument.update(instrument_params)
        format.html { redirect_to instrument_url(@instrument), notice: "Instrument was successfully updated." }
        format.json { render :show, status: :ok, location: @instrument }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @instrument.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /instruments/1 or /instruments/1.json
  def destroy
    @instrument.destroy

    respond_to do |format|
      format.html { redirect_to instruments_url, notice: "Instrument was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_instrument
      @instrument = Instrument.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def instrument_params
      params.require(:instrument).permit(:brand, :model, :description, :condition, :finish, :tiitle, :price, :image)
    end
end

and inside the model (ignore 'tiitle' as i have already done a typo and continue to use it instead of 'title')

instrument.rb

class Instrument < ApplicationRecord
    
    mount_uploader :image, ImageUploader

    belongs_to :user, optional: true
    

    validates :tiitle, :brand, :price, :model, presence: true
    validates :description, length: { maximum: 1000, too_long: "%{count} is the maximum allowed characters" }
    validates :tiitle, length: { maximum: 140, too_long: "%{count} is the maximum allowed characters" } 
    validates :price, numericality: { only_integer: true }, length: { maximum: 7 } 

    BRAND = %w{ Fender Gibson Epiphone ESP Martin Dean Taylor Jackson PRS Ibanez Charvel Washburn }
    FINISH = %w{ Black White Navy Blue Red Clear Satin Yellow Seafoam }
    CONDITION = %w{ New Excellent Mint Used Fair Poor }



end

_form.html.erb

<%= simple_form_for @instrument, html: { multipart: true } do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

  <div class="form-inputs">
  <div class="row ">
    <div class="col mx-auto">
      <div class="card mt-2 mx-auto p-4 bg-light">
        <div class="card-body bg-light">

        <div class = "container">
                          
        <div class="controls">
      
          <div class="row">
            <div class="col-md-10">
              <div class="form-group">
              <%= f.input :tiitle, input_html: {class: "form-control"} %>
              </div>
            </div>

            
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <%= f.input :model, input_html: {class: "form-control"} %>
              </div>
            </div>

            <div class="col-sm-2">
              <div class="form-group">
                <%= f.input :price %>
              </div>
            </div>
          </div> 

        </div>
        </div>

    <%= f.input :description %>

    <%= f.label :condition %>
    <div class="row">
      <div class="col-sm-1">
        <div class="form-group">
            
            <%= f.input_field :condition, collection: Instrument::CONDITION, prompt: "Select Condition" %>
        </div>
      </div>
    </div>


    <%= f.label :brand %>
    <div class="row">
      <div class="col-sm-1">
        <div class="form-group">
          <%= f.input_field :brand, collection: Instrument::BRAND, prompt: "Select Brand" %>
        </div>
      </div>
    </div>


    <%= f.label :finish %>
    <div class="row">
      <div class="col-sm-1">
        <div class="form-group">
          <%= f.input_field :finish, collection: Instrument::FINISH, prompt: "Select Finish" %>   
        </div>
      </div>
    </div>



    <%= f.input :image, as: :file, input_html:{ multiple: true, class:"file-input instrument-image" }, label: false, wrapper: false %>
  </div>  
    </div>
      </div>
        </div>
          </div>


  <div class="form-actions">
    <div class="row">

      <div class="col-sm-1">
        <%= f.button :submit, "Create instrument", class: "btn btn-success create-instrument-btn" %>
      </div>
    

      <div class="col-sm-2">
        <%= link_to "Cancel", instruments_path, class: "btn btn-danger cancel-instrument-btn" %>
      </div>

    </div>
  </div>



<% end %>

image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  version :thumb do
    process resize_to_fit: [400, 300]
  end

  version :default do
    process resize_to_fit: [800, 600]
  end

  # Add an allowlist of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_allowlist
    %w(jpg jpeg gif png)
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end
end

i am a newbie, according to the knowledge what i have understood is that we have to use html: {multipart: true} in the form initializing so that it accepts the uploader as file and permit the ':image' in controller's file and it should work but when i click the "Create" button, it dosen't upload the image and shows unpermitted params in terminal while i submit it and creates a new instrument with all fields except the uploader. Any fixes? :')

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

jeudi 29 septembre 2022

ActiveRecord::HasManyThroughAssociationNotFoundError cannot get the posts for each user for some reason Rails

In the rails console I am inputing User.first.posts and i am getting this error ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :likes in model User from

USER MODEL

class User < ApplicationRecord
    has_secure_password
    has_many :posts
    has_many :comments
    has_many :posts, through: :likes

    validates :name, presence: true, uniqueness: true
end

POSTS MODEL

class Post < ApplicationRecord
belongs_to :user
has_many :comments
has_many :likes
has_many :users, through: :likes
def number_of_comments
    comments.length
end
def number_of_likes
    likes.length
end

end

LIKES MODEL

class Like < ApplicationRecord
belongs_to :user
belongs_to :post
end

Im only showing you the likes model because its popping up in the error but i just want all the posts for each user so if i type User.first.posts all their posts will show up

How can I access these nested attributes in parameters?

I'm trying to get the value of one of the parameters sent, but I'm using nested attributes and when creating an object, the nested attributes have a kind of token, which prevents me from accessing the attributes through the key.

How can I access these nested attributes in parameters?

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xodtke+W96O+hiEH8AvnK4F5XZF5U9b8148YyVTsZX5XNlkdOxmv4RTge+9MmOtfoNLOaUZbcpMcTVxRFSwRUQ==", "comanda"=>{"cliente_id"=>"1", "forma_pagamento_id"=>"1", "R$valor_total"=>"", "status"=>"false", "itens_comandas_attributes"=>{"1664413214142"=>{"produto_id"=>"1", "valor"=>"", "quantidade"=>"", "_destroy"=>"false"}, "1664413217936"=>{"produto_id"=>"2", "valor"=>"", "quantidade"=>"", "_destroy"=>"false"}}}, "commit"=>"Create Comanda"}

Here, in the nested attributes, this token "1664413214142" that contains the values, but if I try to access the "product_id" key, it doesn't return anything:

    puts params[:comanda].has_key?(:itens_comandas_attributes)

true

    puts params[:comanda][:itens_comandas_attributes]

it doesn't return anything

dimanche 25 septembre 2022

Avoid duplicate sidekiq job

I have a worker that runs when the user selects a time. If the user selects a time twice, the worker runs twice. How do I avoid it from being executed multiple times? I mean, If the user selects to be executed after 10 minutes, then deletes this request and again selects to be executed after 10 minutes, the worker executed twice.

class EnableWorker
  include Sidekiq::Worker
  sidekiq_options queue: :general, retry: 0

  def perform(enable_at)
    puts enable_at
  end
end

jeudi 22 septembre 2022

Calling AJAX in Coffeescript

I have an ajax call that works well in a view, but I would like to make it in a coffee script, right inside a datatable call. The code looks like:

    $(document).ready(function () {
    $.ajax({
      type: "GET",
      url: "<%= people_path(format: :json) %>",
      dataType: "json",
      success: function({data}) {
        const user_ids = data.map(user => user.id)
        $("#people-ids").html(user_ids.join());
      }
    });
  });

I am new to coffeescript, so I need some help to finish the method around the mapping section. I could go as far as this:

ajax:
  type: 'GET'
  url: $('#people-datatable').data('source')
  dataType: 'json'
  success: ({data}) ->

I obtain 7 objects in {data}, but i do not know how to continue to retrieve their ID as in JS. can someone help please ?

mercredi 21 septembre 2022

Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted

config.action_mailer.default_url_options = { :host => 'localhost'} 
  ActionMailer::Base.smtp_settings = {
    :user_name => 'xyz@gmail.com',
    :password => 'nico6655',
    :domain => 'gmail.com',
    :address => 'smtp.gmail.com',
    :port => 587,
    :authentication => :plain, 
    :enable_starttls_auto => true,
    :openssl_verify_mode  => 'none'

  }

How to fix the 'SMTP could not authenticate' error?

mardi 20 septembre 2022

Rails partial path when bootstrap tab active

I am building a profile page that contains a navigation tab with 3 tabs(account, settings, and language&display). Each tab renders a partial. What I want to achieve is that for each partial rendered the URL will change as well.

For example when Settings tab is active I want to be on settings_path, and the url: localhost:3000/settings.

my page here

I did not find anything about partials and paths, do you have any idea about this?

Why do I get a syntax error in my ajax based shopping cart?

adding ajax features to cart 1

I am trying to build an online store, and I have opted to include ajax in the shopping cart. I am stuck as I don't understand why ajax is not showing. I am only seeing this error in console which I have failed to understand.

VM1510:2 Uncaught SyntaxError: Private field '#hiding' must be declared in an enclosing class
    at processResponse (rails-ujs.js:281:1)
    at rails-ujs.js:194:1
    at xhr.onreadystatechange (rails-ujs.js:262:1)

dimanche 18 septembre 2022

How to bypass hCaptha with accessibility

Hi I have a rails application built for web scraping our results from the site by entering register ID. But they have updated the site by including hCaptcha so I would like to know how to bypass and fetch the results from the site by looping roll calls( register IDs). Can anyone help me with that, please?

Site: https://jntuaresults.ac.in/view-results?resultSetId=fb1924a4-494e-41ba-a9ad-0aff49cc0064

Roll calls range : 219f1a0501..219f1a0599

https://dashboard.hcaptcha.com/welcome_accessibility

I have seen this cookie setting which works but I need it in the form of a script.

samedi 17 septembre 2022

Ruby on Rails Developer Coding Test [closed]

Please I need help with preparing for the Ruby on Rails coding test assessment for a Ruby on Rails developer position. Please can anyone recommend a very good resource for practice?

vendredi 16 septembre 2022

Websocket fails to start in ruby rails 7.0.4

I have been trying to set up an action cable with ruby on rails version 7.0.4 and fail to do In the app/channels/application_cable.rb my configuration file is as below. As per official documentation, every connection should be identified, so I decided to identify that via random string:

module ApplicationCable class Connection < ActionCable::Connection::Base identified_by: random_string

def random_string
  return SecureRandom.base64()
end

end end

I have only a single channel, called room_channel for learning purposes:

class RoomChannel < ApplicationCable::Channel

def subscribed stream_from "room_channel" end

def unsubscribed # Any cleanup needed when channel is unsubscribed end end

in the app/javascript/channels/consumer.js I created below configuration and set up at least 1 consumer, so my app could work

import { createConsumer } from "@rails/actioncable"

export default createConsumer()

createConsumer(getWebSocketURL)

function getWebSocketURL() {
  return "ws://159.61.241.9:8000/cable"
}

My config/environments/development.rb file is as below for action cable related settings:

config.action_cable.url = "ws://localhost:6379/cable"
  config.action_cable.allowed_request_origins = ['http://159.65.241.9:8000']
  config.action_cable.mount_path="ws://localhost:6379/cable"

my cable.yml file in the config as below:

    development:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>


test:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>


production:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
  channel_prefix: action_cable_chat_app_production

I started up the redis server already. The error I end up with is as below: enter image description here

Can someone please help me why WebSocket tries to start at 8000 port even though I mount the server in 6379 in the config file ?

jeudi 15 septembre 2022

NoMethodError : Undefined method in NilClass

I'm currently accessing the same piece of code from two routes in two different files. I have the code in file X which is rendering or accessing by a link. I created a file Y and copy pasted same code present in X and rendering this particular file from a different link in routes file. For example - two different links -

 get '/holdings/:holding_name/board ,to : 'dashboard/x

 get '/scoldings/:scolding_name/board ,to : 'dashboard/y 

I've created file Y and copy pasted code from file X which has a method named .operations. Please don't ask me why I have to create file Y when I can render to file X itself. I have to do it. So, I'm getting an error :

undefined method `operations' for nil:NilClass

when trying to call file Y. But everything is file when I'm accessing file X. Can someone please explain the root cause. Thankyou!

How is different data shown to different users on the same URL?

I'm currently dealing with a situation where I need to display same URL to two types of users for viewing different data on the URL. Here is the background - Initially we had two different URLs for Metrics of type 1 and Metrics of type 2. So, in order to display which URL to which user we simply had an if condition something like this-

<%= if User1? %>
DISPLAY URL A
<%=end%>
<%= if User2? %>
DISPLAY URL B
<%=end%>

Later situation - For some reason the content(Basically metrics here) from URL B have been moved to URL A now (which is both types of metrics are present in single link here) Problem - Now we want to present only single URL to both types of users 1&2. However, when USER 1 is accessing he should be able to view all types of metrics in the URL. But when USER 2 is viewing the URL he should not view a particular metric (lets say type 2) but should see all the rest. So, in a nut shell we need to provide same URL for both users but they have to view different content and this has to be achieved with a simple IF statement something like -

<%= if User1? %>
<%= if User2? %>
DISPLAY URL A and block the content of metric type 2.
<end>
Display URL A with all metrics
<%=end%>

P.S - we have two types of metrics now in the consolidated link and both of them have different code-files from where they are fetching the code. I'm assuming if we can block accessing a file which has metric type 2 with an if condition then might solve problem. But can someone help me with this please ? Thank you!

My question - Can someone translate this pseudo code to actual code that works? Would be really really helpful.

How to display same URL by hiding a specific data inside URL to two different users

I’m trying to display a particular URL to users which consists of three metrics(dashboards) where they are fetching the code from three separate code-files for each metric.Here we have two types of users - USER1 &USER2.USER2 should not have the access/ should not be able to see a particular metric out of three but still be able to access the same URL to see other two metrics. USER 1 should be able to access the same URL and be able to see all the three metrics. So, let’s assume that particular metric which USER2 is supposed to not see is Analytics_metric from file “Analytics_metric.html.erb”.I want to achieve this by using if statements to validate USER1 & USER 2 from watching the metrics inside same URL for example- URL :https:/example/metrics.

Here is the code which I’m using currently to display the URL link to both USERS (Not performing any operations here) -


<%# if USERS?%>
<%= a_link url:example/metrics do%>
Metrics dashboards //Title of link
<%=end%>

As we can see the current code is accessible by both USER1 & USER 2 in order to display all three metrics when they just click the URL. But we don’t want this to happen as USER2 is also able to see the Analytics_metric which should not be seen.

How to Create table in ruby on rails [closed]

How to create a table like this one in the picture using ruby (html) and also using radio_button ? I have tried in the view to create just a simple table not like this, but also I have searched for it in many questions and did not find a clear answer for it. picture for the table

mercredi 14 septembre 2022

JSON key reducer and formtter in Ruby

I am facing a situation where it seems helpful to have a gem that can format the JSON that comes as a response from any API. For example I may make a call to fetch some data but I don't need all the fields, instead I need to create a new JSON by parsing the original one to only include some fields and also be able to select only some of nested fields from arrays or array of arrays inside that JSON. The result of the reduced JSON can be a JSON that has only one level of nesting. Can you please help me if there is an existing gem in Ruby to do this?

dimanche 11 septembre 2022

Undefined method error in Ruby on rails. However the method doesn't exist at all

I'm getting the following error:

undefined method `posix_group' for ["494149846749", "12"]:Array. 

However I don't have a method named possix_group in my entire code package. But I do have a piece of code

posix_group = application.posix_group

Also some annotations like @possix_group. I can't find a method named with the above to solve the problem.

While working on Ruby on Rails I came across this piece of line. Can someone explain this [closed]

set_name_prod = Rails.configuration.material_set[:general][:prod] % application.client_token Can someone take time in helping me understand please.

Rails Devise failed attempts unlock customer handling

I currently use devise with config.unlock_strategy = :email But I want to change it to none, so the template email is not sent, and I use my own logic. but my question is - how do I know the number of failed attempts is reached? Do I need to constantly check on my own - or is there some function I can implement that is automatically called upon maximum_attempts reached? Thanks

dimanche 4 septembre 2022

Fail to install Gollum on MacOS BigSUr. Gem::Ext::BuildError: ERROR: Failed to build gem native extension

I want to install Gollum in my MacOS Big Sur

I already follow the instruction on Github. My Ruby and gem version is as follows

ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [arm64-darwin20]
gem 3.2.3

When I write sudo bundle install, I found the error message in the log below :

Fetching gem metadata from https://rubygems.org/.........
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies...
Using rake 13.0.6
Using concurrent-ruby 1.1.10
Using racc 1.6.0
Using public_suffix 5.0.0
Using rack 2.2.4
Using regexp_parser 2.5.0
Using childprocess 4.1.0
Using crass 1.0.6
Using execjs 2.8.1
Using ffi 1.15.5
Using json 2.6.2
Using github-markup 4.0.1
Using mime-types 1.25.1
Using rouge 3.30.0
Using unf_ext 0.0.8.2
Using builder 3.2.4
Using bundler 2.2.3
Using matrix 0.4.2
Using mini_mime 1.1.2
Using stringio 3.0.2
Using rb-fsevent 0.11.2
Using ruby2_keywords 0.0.5
Using tilt 2.0.11
Using multi_json 1.15.0
Using therubyrhino_jar 1.7.8
Using useragent 0.16.10
Using webrick 1.7.0
Using metaclass 0.0.4
Using ruby-progressbar 1.11.0
Using power_assert 2.0.1
Using rubyzip 2.3.2
Using websocket 1.2.9
Using shoulda-context 1.2.2
Using i18n 1.12.0
Using tzinfo 2.0.5
Using addressable 2.8.1
Using rack-test 0.6.3
Using gemojione 4.3.3
Using rb-inotify 0.10.1
Using rack-protection 2.2.2
Using nokogiri 1.13.8 (arm64-darwin)
Fetching rugged 1.1.1
Using sprockets 3.7.2
Using unf 0.1.4
Using psych 4.0.4
Using sass-listen 4.0.0
Using mustermann 2.0.2
Using therubyrhino 2.1.2
Using mocha 1.8.0
Using test-unit 3.3.9
Using uglifier 4.2.0
Using rdoc 6.4.0
Using sass 3.7.4
Using sinatra 2.2.2
Using sprockets-helpers 1.4.0
Using minitest 5.16.3
Using ansi 1.5.0
Using rexml 3.2.5
Using mustache 0.99.8
Using activesupport 7.0.3.1
Using twitter-text 1.14.7
Using xpath 3.2.0
Using loofah 2.18.0
Using octicons 12.1.0
Using kramdown 2.4.0
Using mustache-sinatra 1.0.1
Using rss 0.2.9
Using sinatra-contrib 2.2.2
Using minitest-reporters 1.3.8
Using selenium-webdriver 4.4.0
Using capybara 3.37.1
Using kramdown-parser-gfm 1.1.0
Using shoulda-matchers 3.1.3
Using shoulda 3.6.0
Installing rugged 1.1.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/gems/3.0.0/gems/rugged-1.1.1/ext/rugged
/Users/fendy/.rvm/rubies/ruby-3.0.0/bin/ruby -I /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0 -r ./siteconf20220904-7725-ezc495.rb extconf.rb
checking for gmake... yes
checking for cmake... yes
checking for pkg-config... yes
-- The C compiler identification is AppleClang 13.0.0.13000029
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /Library/Developer/CommandLineTools/usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Found PkgConfig: /opt/homebrew/bin/pkg-config (found version "0.29.2") 
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Success
-- Found Threads: TRUE  
-- Performing Test HAVE_STRUCT_STAT_ST_MTIM
-- Performing Test HAVE_STRUCT_STAT_ST_MTIM - Failed
-- Performing Test HAVE_STRUCT_STAT_ST_MTIMESPEC
-- Performing Test HAVE_STRUCT_STAT_ST_MTIMESPEC - Success
-- Performing Test HAVE_STRUCT_STAT_MTIME_NSEC
-- Performing Test HAVE_STRUCT_STAT_MTIME_NSEC - Failed
-- Performing Test HAVE_STRUCT_STAT_NSEC
-- Performing Test HAVE_STRUCT_STAT_NSEC - Success
-- Performing Test IS_WALL_SUPPORTED
-- Performing Test IS_WALL_SUPPORTED - Success
-- Performing Test IS_WEXTRA_SUPPORTED
-- Performing Test IS_WEXTRA_SUPPORTED - Success
-- Performing Test IS_WDOCUMENTATION_SUPPORTED
-- Performing Test IS_WDOCUMENTATION_SUPPORTED - Success
-- Performing Test IS_WNO_DOCUMENTATION_DEPRECATED_SYNC_SUPPORTED
-- Performing Test IS_WNO_DOCUMENTATION_DEPRECATED_SYNC_SUPPORTED - Success
-- Performing Test IS_WNO_MISSING_FIELD_INITIALIZERS_SUPPORTED
-- Performing Test IS_WNO_MISSING_FIELD_INITIALIZERS_SUPPORTED - Success
-- Performing Test IS_WSTRICT_ALIASING_SUPPORTED
-- Performing Test IS_WSTRICT_ALIASING_SUPPORTED - Success
-- Performing Test IS_WSTRICT_PROTOTYPES_SUPPORTED
-- Performing Test IS_WSTRICT_PROTOTYPES_SUPPORTED - Success
-- Performing Test IS_WDECLARATION_AFTER_STATEMENT_SUPPORTED
-- Performing Test IS_WDECLARATION_AFTER_STATEMENT_SUPPORTED - Success
-- Performing Test IS_WSHIFT_COUNT_OVERFLOW_SUPPORTED
-- Performing Test IS_WSHIFT_COUNT_OVERFLOW_SUPPORTED - Success
-- Performing Test IS_WUNUSED_CONST_VARIABLE_SUPPORTED
-- Performing Test IS_WUNUSED_CONST_VARIABLE_SUPPORTED - Success
-- Performing Test IS_WUNUSED_FUNCTION_SUPPORTED
-- Performing Test IS_WUNUSED_FUNCTION_SUPPORTED - Success
-- Performing Test IS_WINT_CONVERSION_SUPPORTED
-- Performing Test IS_WINT_CONVERSION_SUPPORTED - Success
-- Performing Test IS_WFORMAT_SUPPORTED
-- Performing Test IS_WFORMAT_SUPPORTED - Success
-- Performing Test IS_WFORMAT_SECURITY_SUPPORTED
-- Performing Test IS_WFORMAT_SECURITY_SUPPORTED - Success
-- Performing Test IS_WMISSING_DECLARATIONS_SUPPORTED
-- Performing Test IS_WMISSING_DECLARATIONS_SUPPORTED - Success
-- Looking for futimens
-- Looking for futimens - found
-- Checking prototype qsort_r for HAVE_QSORT_R_BSD
-- Checking prototype qsort_r for HAVE_QSORT_R_BSD - True
-- Checking prototype qsort_r for HAVE_QSORT_R_GNU
-- Checking prototype qsort_r for HAVE_QSORT_R_GNU - False
-- Looking for qsort_s
-- Looking for qsort_s - not found
-- Looking for clock_gettime in rt
-- Looking for clock_gettime in rt - not found
-- Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR) 
-- Found Security /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/Security.framework
-- Looking for SSLCreateContext in /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/Security.framework
-- Looking for SSLCreateContext in /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/Security.framework - found
-- Found CoreFoundation /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/CoreFoundation.framework
-- Found PCRE: /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/usr/lib/libpcre.tbd  
-- Looking for dirent.h
-- Looking for dirent.h - found
-- Looking for stdint.h
-- Looking for stdint.h - found
-- Looking for inttypes.h
-- Looking for inttypes.h - found
-- Looking for sys/stat.h
-- Looking for sys/stat.h - found
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for unistd.h
-- Looking for unistd.h - found
-- Looking for windows.h
-- Looking for windows.h - not found
-- Looking for bcopy
-- Looking for bcopy - found
-- Looking for memmove
-- Looking for memmove - found
-- Looking for strerror
-- Looking for strerror - found
-- Looking for strtoll
-- Looking for strtoll - found
-- Looking for strtoq
-- Looking for strtoq - found
-- Looking for _strtoi64
-- Looking for _strtoi64 - not found
-- Looking for stddef.h
-- Looking for stddef.h - found
-- Check size of long long
-- Check size of long long - done
-- Check size of unsigned long long
-- Check size of unsigned long long - done
-- Performing Test IS_WNO_UNUSED_FUNCTION_SUPPORTED
-- Performing Test IS_WNO_UNUSED_FUNCTION_SUPPORTED - Success
-- Performing Test IS_WNO_IMPLICIT_FALLTHROUGH_SUPPORTED
-- Performing Test IS_WNO_IMPLICIT_FALLTHROUGH_SUPPORTED - Success
-- http-parser version 2 was not found or disabled; using bundled 3rd-party sources.
-- Performing Test IS_WIMPLICIT_FALLTHROUGH_1_SUPPORTED
-- Performing Test IS_WIMPLICIT_FALLTHROUGH_1_SUPPORTED - Failed
-- Found ZLIB: /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/usr/lib/libz.tbd (found version "1.2.11") 
-- Checking for module 'libssh2'
--   Package 'libssl', required by 'libssh2', not found
-- LIBSSH2 not found. Set CMAKE_PREFIX_PATH if it is installed outside of the default search path.
-- Checking for module 'heimdal-gssapi'
--   No package 'heimdal-gssapi' found
-- Could NOT find GSSAPI (missing: GSSAPI_LIBRARIES) 
-- Found GSS.framework /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/GSS.framework
-- Looking for iconv_open
-- Looking for iconv_open - not found
-- Found Iconv: -L/Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/usr/lib -liconv
-- Enabled features:
 * nanoseconds, whether to use sub-second file mtimes and ctimes
 * tracing, tracing support
 * threadsafe, threadsafe support
 * HTTPS, using SecureTransport
 * SHA, using CollisionDetection
 * regex, using bundled PCRE
 * http-parser, http-parser support (bundled)
 * zlib, using system zlib
 * ntlmclient, NTLM authentication support for Unix
 * iconv, iconv encoding conversion support

-- Disabled features:
 * debugpool, debug pool allocator
 * SSH, SSH transport support
 * SPNEGO, SPNEGO authentication support

-- Configuring done
-- Generating done
-- Build files have been written to: /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/gems/3.0.0/gems/rugged-1.1.1/vendor/libgit2/build
 -- /opt/local/bin/gmake
checking for -lgit2... yes
checking for git2.h... yes
creating Makefile

current directory: /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/gems/3.0.0/gems/rugged-1.1.1/ext/rugged
make "DESTDIR=" clean
/Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/rubygems.rb:281:in `find_spec_for_exe': can't find gem make (>= 0.a) with executable make (Gem::GemNotFoundException)
    from /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/rubygems.rb:300:in `activate_bin_path'
    from /Users/fendy/.rvm/gems/ruby-3.0.0/bin/make:23:in `<main>'

current directory: /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/gems/3.0.0/gems/rugged-1.1.1/ext/rugged
make "DESTDIR="
/Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/rubygems.rb:281:in `find_spec_for_exe': can't find gem make (>= 0.a) with executable make (Gem::GemNotFoundException)
    from /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/rubygems.rb:300:in `activate_bin_path'
    from /Users/fendy/.rvm/gems/ruby-3.0.0/bin/make:23:in `<main>'

make failed, exit code 1

Gem files will remain installed in /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/gems/3.0.0/gems/rugged-1.1.1 for inspection.
Results logged to /Users/fendy/.rvm/rubies/ruby-3.0.0/lib/ruby/gems/3.0.0/extensions/arm64-darwin-20/3.0.0/rugged-1.1.1/gem_make.out

An error occurred while installing rugged (1.1.1), and Bundler cannot continue.
Make sure that `gem install rugged -v '1.1.1' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  gollum was resolved to 5.3.0, which depends on
    gollum-lib was resolved to 5.2, which depends on
      gollum-rugged_adapter was resolved to 1.1.2, which depends on
        rugged

I already read the stackoverflow topic here but it seems different problem with mine. I think my problem is to find the appropriate gem of ruby which I can not figure it out which one. Therefore I would like to ask this question, perhaps someone here has already encounter and solve similar problem.

Thank you

vendredi 2 septembre 2022

Custom form for active admin is not displaying

I have added a piece of code in my active admin model for input form, but weirdly, it's not getting displayed, instead, it's showing the default form. Neither it's showing any error nor displaying my custom form.

form do |f|
f.inputs do
  f.input :email
  f.input :phone
  f.input :gender
  f.input :birthday
  f.input :password
  f.input :password_confirmation
  f.input :us_citizen
  f.input :invitation_limit
end
f.actions

end

jeudi 1 septembre 2022

ArgumentError: tried to create Proc object without a block

How can I resolve the following error:

$ rails db:migrate
Calling `DidYouMean::SPELL_CHECKERS.merge!(error_name => spell_checker)' has been deprecated. Please call `DidYouMean.correct_error(error_name, 
spell_checker)' instead.
Calling `DidYouMean::SPELL_CHECKERS.merge!(error_name => spell_checker)' has been deprecated. Please call `DidYouMean.correct_error(error_name, 
spell_checker)' instead.
rails aborted!
ArgumentError: tried to create Proc object without a block
D:/Projects/lms-2021/config/application.rb:9:in `<top (required)>'
D:/Projects/lms-2021/Rakefile:4:in `require_relative'
D:/Projects/lms-2021/Rakefile:4:in `<top (required)>'
bin/rails:9:in `require'
bin/rails:9:in `<main>'
(See full trace by running task with --trace)

These are the logs after rails db:migrate --trace:

$ rails db:migrate --trace
Calling `DidYouMean::SPELL_CHECKERS.merge!(error_name => spell_checker)' has been deprecated. Please call `DidYouMean.correct_error(error_name, spell_checker)' instead.
Calling `DidYouMean::SPELL_CHECKERS.merge!(error_name => spell_checker)' has been deprecated. Please call `DidYouMean.correct_error(error_name, spell_checker)' instead.
rails aborted!
ArgumentError: tried to create Proc object without a block
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/aws-sdk-core-2.9.24/lib/aws-sdk-core.rb:472:in `new'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/aws-sdk-core-2.9.24/lib/aws-sdk-core.rb:472:in `service_added'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/aws-sdk-core-2.9.24/lib/aws-sdk-core.rb:510:in `<module:Aws>'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/aws-sdk-core-2.9.24/lib/aws-sdk-core.rb:18:in `<top (required)>'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:292:in `require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:292:in `block in require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:258:in `load_dependency'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:292:in `require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/aws-sdk-resources-2.9.24/lib/aws-sdk-resources.rb:1:in `<top (required)>'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:292:in `require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:292:in `block in require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:258:in `load_dependency'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/activesupport-5.1.7/lib/active_support/dependencies.rb:292:in `require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/aws-sdk-2.9.24/lib/aws-sdk.rb:1:in `<top (required)>'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.2.3/lib/bundler/runtime.rb:66:in `require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.2.3/lib/bundler/runtime.rb:66:in `block (2 levels) in require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.2.3/lib/bundler/runtime.rb:61:in `each'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.2.3/lib/bundler/runtime.rb:61:in `block in require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.2.3/lib/bundler/runtime.rb:50:in `each'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.2.3/lib/bundler/runtime.rb:50:in `require'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.2.3/lib/bundler.rb:174:in `require'
D:/Projects/lms-2021/config/application.rb:9:in `<top (required)>'
D:/Projects/lms-2021/Rakefile:4:in `require_relative'
D:/Projects/lms-2021/Rakefile:4:in `<top (required)>'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/rake-13.0.3/lib/rake/rake_module.rb:29:in `load'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/rake-13.0.3/lib/rake/rake_module.rb:29:in `load_rakefile'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/rake-13.0.3/lib/rake/application.rb:703:in `raw_load_rakefile'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/rake-13.0.3/lib/rake/application.rb:104:in `block in load_rakefile'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/rake-13.0.3/lib/rake/application.rb:186:in `standard_exception_handling'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/rake-13.0.3/lib/rake/application.rb:103:in `load_rakefile'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/railties-5.1.7/lib/rails/commands/rake/rake_command.rb:20:in `block in perform'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/rake-13.0.3/lib/rake/application.rb:186:in `standard_exception_handling'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/railties-5.1.7/lib/rails/commands/rake/rake_command.rb:18:in `perform'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/railties-5.1.7/lib/rails/command.rb:46:in `invoke'
D:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/railties-5.1.7/lib/rails/commands.rb:16:in `<top (required)>'
bin/rails:9:in `require'
bin/rails:9:in `<main>'

This is the application.rb file where the error is shown:

require 'uri'
require "uri/generic"
require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)


module Ilms
  class Application < Rails::Application    

    config.to_prepare do
      # Load application's model / class decorators
      Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
        Rails.configuration.cache_classes ? require(c) : load(c)
      end

      # Load application's view overrides
      Dir.glob(File.join(File.dirname(__FILE__), "../app/overrides/*.rb")) do |c|
        Rails.configuration.cache_classes ? require(c) : load(c)
      end
    end
    
    config.assets.initialize_on_precompile = false    
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

  end
end

I am not understanding where is the error and how to fix it. There seems no error in my code. The logs with --trace are showing the error occured in lib/ruby/gems/3.1.0/gems/aws-sdk-core-2.9.24/lib/aws-sdk-core.rb:472:in `new' which callback = Proc.new .

  • Database : postgresql
  • gem 'pg' already installed
  • rails v 5.1.7
  • ruby v 3.1.2
  • windows 10 pro
  • git bash terminal