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=> *}}