lundi 30 novembre 2020

Could not run the `identify` command. Please install ImageMagick

I am using Paperclip and getting this error on the deployed site, not on my local server. And that's why it is becoming more difficult for me to get out of this.

A Paperclip::Errors::CommandNotFoundError occurred in images#update:
enter code hereCould not run the `identify` command. Please install ImageMagick.

I have tried these solutions but was not able to fix this (For ubuntu):

  1. Ran apt-get install imagemagick
  2. I don't use brew. So, won't be able to use brew install imagemagick
  3. Added and deployed these lines to paperclip_options.yml

:image_magick_path: '/opt/ImageMagick/bin' :command_path: '/opt/ImageMagick/bin'

Can anyone suggest how to resolve this error?

vendredi 27 novembre 2020

View action should show same response which I get on form submission

I have registration form , once I have submit that form , I was getting some response. I want to show same response on view action. Currently, I have registration page which have two tabs, one is for registration form and other is for post register activity form.where second tab is disabled till I have submitted the registration form. I am able to submit a form and getting response as well, now I want show same response on view action, How should I achieve that in rails web project ? How should my routes work in that case ?

Match request URL params with rails routes via recognize_path

I want to check if any incoming request actually exists in routes.rb as an entry via recognize_path like this

def path_exists?(path)
  Rails.application.routes.recognize_path(path)
  true
  rescue
   false
end

This works for most URLs but if the URL has a parameter, then it fails to recognize it.

Example:

In routes.rb, say I have an entry like this

put "foo/bar/:param" => "foo#bar"

and the incoming request URL is of the form /foo/bar/5

Then the function recognize_path doesn't recognize the URL as the value of the parameter is 5 but it is matched with :param

How do I match requests that have parameters to their entries in routes.rb using recognize_path or any other similar function?

Reason

I'm filtering out malicious attempts to hit the server using random URLs like /dump.sql.tar.gz, /conf.xz, etc using the gem rack::attack and throttling requests whose URLs are not a part of routes.rb. Hence the above problem.

Ruby on Rails - Criteria - Mongoid - where condition with 2 by 2 columns

I'm working with RoR + MongoDB (Mongoid) and I need to apply a filter using or condition by 2 columns.

I saw some recommendations like this one but didn't work.

query = query.where(name: /#{attributes[:name]}/i).or(query.where(email: /#{attributes[:email]}/i))

If I use this one, looks like the or will be applied for all conditions:

query = query.where(name: /#{attributes[:name]}/i).or(email: /#{attributes[:email]}/i)

Anyone has any suggestion?

jeudi 26 novembre 2020

Get this "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" combination for ruby

I have this java code for encryption and decryption, which I want to change/convert to Ruby code. I looked up in OpenSSL gem but dint find the "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" combination available for ruby. How do I implement it?

public class EncryptDecryptService {
    
    public String encryptRequestObject(RequestObject requestObject) throws UnsupportedEncodingException, FileNotFoundException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        PublicKey publicKey = getPublicKey(requestObject.getKeyFilename());
        byte[] message = requestObject.getString().getBytes("UTF-8");
        byte[] secret = encrypt(publicKey, message);
        return Base64.encodeBase64String(secret);
    }
    
    public String decryptRequestObject(RequestObject requestObject) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        PrivateKey privateKey = getPrivateKey(requestObject.getKeyFilename(), requestObject.getKeyPassword());
        byte[] cipherText = Base64.decodeBase64(requestObject.getString());
        byte[] decrypted = decrypt(privateKey, cipherText);
        return new String(decrypted, "UTF-8");
    }
    
    private PublicKey getPublicKey(String filename) throws FileNotFoundException, CertificateException {
        FileInputStream fin = new FileInputStream(filename);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) factory.generateCertificate(fin);
        PublicKey publicKey = certificate.getPublicKey();
        return publicKey;
    }
    
    private PrivateKey getPrivateKey(String filename, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
        FileInputStream fin = new FileInputStream(filename);
        KeyStore ks = KeyStore.getInstance("pkcs12");
        ks.load(fin, password.toCharArray());
        String str = ks.aliases().nextElement();
        PrivateKey privateKey = (PrivateKey) ks.getKey(str, password.toCharArray());
        return privateKey;
    }
    
    private byte[] encrypt(PublicKey key, byte[] plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(plainText);
    }
    
    private byte[] decrypt(PrivateKey key, byte[] cipherText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }
}

mercredi 25 novembre 2020

Find records have count of association > n

class PurchaseOrder < ApplicationRecord
  has_many :purchase_order_materials 
end 
class PurchaseOrderMaterial < ApplicationRecord
  belongs_to :purchase_order
  belongs_to :material
end

I have this query:

PurchaseOrderMaterial
  .includes(:purchase_order, :material)
  .where("purchase_orders.provider_id IS NULL AND purchase_orders.status = ? 
          AND (purchase_orders.is_waiting != ? 
               OR purchase_orders.is_waiting IS NULL)", 
         PurchaseOrder.possibleStatus.first, true)

All i want it's filter results to purchase_order.purchase_order_materials.count > 1. Some way to achieve it?

mardi 24 novembre 2020

Weird time.beginning_of_month rails 3 behavior

I am working on this query:

Student.where(created_at: time.beginning_of_month..time). Let's say the time here is: `15/10/2020 00:00:00`

I thought this is supposed to return the created students from 1/10/2020 00:00:00 to 15/10/2020 00:00:00 because time.beginning_of_month returns 1/10/2020 00:00:00

However, it returns me the created students from 30/09/2020 22:00:00 to 15/10/2020 00:00:00

I have checked with other months and I get the same results. Somehow, it always returns me the records starting from the last day of the previous month, not the first day of the current month

I am using Rails 3.2.2 and Ruby 2.1.5

samedi 21 novembre 2020

Gems are not found inside Docker container After sourcing RVM path

scenario1

So the problem I am facing like after building the docker images. If I am going inside the docker container and doing GEM_PATH=$GEM_HOME gem list it is not showing all the gems installed at the time of building the image. it is showing only a few gems.

scenario2

If I am not sourcing the RVM path inside the Dockerfile. Then If I am going inside the docker container and doing GEM_PATH=$GEM_HOME gem list then it is showing all the gems.

Can anyone please explain to me why this is happening and how I should install and source RVM? So I can see all the gems inside the container. Basically, I want the scenario1 should work. Thanks

Below is my Dockerfile

RUN apt-get update -qq && apt-get install -y sudo && apt-get install -y build-essential && apt-get install -y apt-utils && apt-get install -y git
RUN gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB && \curl -sSL https://get.rvm.io | sudo bash -s stable --ruby && echo 'source /usr/local/rvm/scripts/rvm' >> /etc/bash.bashrc
RUN /bin/bash -l -c 'gem install bundler -v 1.17.3'
RUN /bin/bash -l -c 'gem install rails --version=5.2.4.1'
WORKDIR /app
RUN bundle config build.nokogiri --use-system-libraries
RUN bundle config set path 'vendor/bundle'
COPY Gemfile Gemfile.lock ./
ARG SSH_KEY
# Make ssh dir
RUN mkdir /root/.ssh/
# Copy ssh
RUN echo "$SSH_KEY" > /root/.ssh/id_rsa && \
   chmod 0600 /root/.ssh/id_rsa
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts
RUN bundle install
COPY . ./
EXPOSE 80:80
CMD rails s -p 80 -b '0.0.0.0' -e qa```


vendredi 20 novembre 2020

Create multiple objects while seeding in Ruby on Rails

I have the following seed file that creates many animals which are then added to the animal_store object

animal_store_seeder:

animal1 = create(:animal)
animal2 = create(:animal)
animal3 = create(:animal)

create(
  :animal_store,
  json: {
    "animals": {
      animal1.id=> {
       }, 
      animal2.id =>{
    }
   ... 
  }
}    

So far this works. However, I want to create a store with at least 20 animals. I don't think creating each variable is the correct way to go. Is there a better way to instantiate more animals and adding them to the animal_store without having to create them one at a time?

mercredi 18 novembre 2020

rspec parallel tests without database

I'm using RSpec as an API test harness that does not have a database during testing, and would like to parallelize the runs. I've tried https://github.com/grosser/parallel_tests but the rake task fails when there is no database with Don't know how to build task "'parallel:spec'".

I then moved to the deprecated https://github.com/yuku/parallel-rspec which worked, but it's not passing the arguments I've been using to filter tests correctly.

For example, if I had 10 tests, 2 of which had metadata feature=search would historically run:

bundle exec rspec --tag feature:search

And only those 2 tests would be run.

Now running

`` bundle exec parallel-rspec spec --tag feature:search

still runs all 10 tests.

How can I split up my specs into parallel runs while still preserving the ability to filter by metadata?

mardi 17 novembre 2020

No such file or directory - java rake aborted

I'm having a rails project running properly on my local machine but when I deploy it on heroku I get the error below. I seem not to understand what I'm not doing well. Initially, the project was using gem bootstrap-will_paginate, I removed it and switched to gem bootstrap. Right now as I have mentioned above, locally, the project is running as expected but when I try to deploy to heroku, I run into the error below. Any assistance will be highly appreciated. Thanks

       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-6128dd44fed3a046ff8d835d677e0a837c70c64dc1c944b7edfde04eb8d8b879.eot
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-6128dd44fed3a046ff8d835d677e0a837c70c64dc1c944b7edfde04eb8d8b879.eot.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-f9853ad337d523c0b35fe7ac306268a7035ce0ff7624710ed8b39c2b88b20a33.eot
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-f9853ad337d523c0b35fe7ac306268a7035ce0ff7624710ed8b39c2b88b20a33.eot.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-e0e3c4af28348d721f8af603595c15d273a56f2b03392f9a413255fe5635f536.eot
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-e0e3c4af28348d721f8af603595c15d273a56f2b03392f9a413255fe5635f536.eot.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-e2749cb24a77208abdd9fda35f0d14f091948c44d21f977c8048a3b13e4beccb.svg
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-e2749cb24a77208abdd9fda35f0d14f091948c44d21f977c8048a3b13e4beccb.svg.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-d42a64dc349a98075e8be12587943f2bd52065a8bb18960d7dc7390b535117e0.svg
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-d42a64dc349a98075e8be12587943f2bd52065a8bb18960d7dc7390b535117e0.svg.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-1a46e780ce5beb6507d62af8b20a92b33c8f042e87c612f4bbf8330bfc353419.svg
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-1a46e780ce5beb6507d62af8b20a92b33c8f042e87c612f4bbf8330bfc353419.svg.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-404d6083193e569bc5c28c7b1bc0e13ece80c6e0f5a50ad8e9633f48f3c09155.ttf
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-404d6083193e569bc5c28c7b1bc0e13ece80c6e0f5a50ad8e9633f48f3c09155.ttf.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-5e811f0b32d488b9a183b77cfc7ac1ef44b3ea7aaed014e83975dfe597d221f6.ttf
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-5e811f0b32d488b9a183b77cfc7ac1ef44b3ea7aaed014e83975dfe597d221f6.ttf.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-2caded242c04139761742fe0cda7f6592df1b6686857532c8a7c2e2536b976e4.ttf
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-2caded242c04139761742fe0cda7f6592df1b6686857532c8a7c2e2536b976e4.ttf.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-a0375c054a0041bd58e2a0bf7fa3df7c3904bfc4f790fd24e32ff3ee70fd0eef.woff
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-6799c999e422710f40f70a60a6138fc38106226c44d7bd1b1023f5bb65befef9.woff
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-aab971ade1633ab836222074ceae0aad8a082d900908f27491b221d6e83998ca.woff
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-71b3ce72680f4183d28db86b184542051fd533bb1146933233e4f6a20cf98cba.woff2
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-ce20ed8a323117c8a718ff1ddc6dabb997373b575a8e896f2bf02b846c082c9d.woff2
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-6b555920e358f8a25a422988b448615c33bcccb4f932e8331cebfc8e2a737fc7.woff2
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/flut-086c6ba8919955ef94b7c049b9870b6fd5026b55ea17d8659d1b5e26c74c6b1c.png
       /tmp/build_52cf5ac5_/bin/rake: No such file or directory - java
       rake aborted!
       Command 'java -jar /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/../yuicompressor-2.4.8.jar --type css --charset utf-8 /tmp/yui_compress20201117-409-dud2hb' returned non-zero exit status
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/compressor.rb:106:in `block in compress'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/compressor.rb:141:in `streamify'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/compressor.rb:86:in `compress'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/yui_compressor.rb:49:in `call'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/yui_compressor.rb:28:in `call'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:75:in `call_processor'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:57:in `block in call_processors'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:56:in `reverse_each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:56:in `call_processors'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:134:in `load_from_unloaded'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:60:in `block in load'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:317:in `fetch_asset_from_dependency_cache'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:44:in `load'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/cached_environment.rb:20:in `block in initialize'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/cached_environment.rb:47:in `load'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/base.rb:66:in `find_asset'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/base.rb:73:in `find_all_linked_assets'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/manifest.rb:142:in `block in find'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:114:in `block (2 levels) in logical_paths'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:228:in `block in stat_tree'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:212:in `block in stat_directory'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:209:in `each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:209:in `stat_directory'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:227:in `stat_tree'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:105:in `each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:105:in `block in logical_paths'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:104:in `each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:104:in `logical_paths'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/manifest.rb:140:in `find'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/manifest.rb:186:in `compile'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-rails-3.2.2/lib/sprockets/rails/task.rb:67:in `block (3 levels) in define'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/rake/sprocketstask.rb:147:in `with_logger'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-rails-3.2.2/lib/sprockets/rails/task.rb:66:in `block (2 levels) in define'
       Tasks: TOP => assets:precompile
       (See full trace by running task with --trace)
 !
 !     Precompiling assets failed.
 !
 !     Push rejected, failed to compile Ruby app.
 !     Push failed

Any assistance will be highly welcome

lundi 16 novembre 2020

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "courses" WHERE "courses"."Id"

routes.rb
    Rails.application.routes.draw do
          get "students" => "students#index"
          get "students/new" => "students#new"
          post "students" => "students#create"
        
          get "courses" => "courses#index"
          get "courses/new" => "courses#new"
          post "courses" => "courses#create"
        
          get "students/:id" => "students#show"
          get "courses/:id/students" => "courses#students"
          get "courses/:id/assignments" => "courses#assignments"
          get "courses/:id/assignments/new" => "assignments#new"
          post "courses/:id/assignments" => "assignments#create"
        
          get "courses/:id/edit" => "courses#edit"
          patch "courses/:id" => "courses#update"
          delete "courses/:id" => "courses#destroy"
        
        get "students/:id/edit" => "students#edit"
        patch "students/:id" => "students#update"
        delete "students/:id" => "students#destroy" 
        end 

CourseController.rb
        class CoursesController < ApplicationController
        def index
        @courses = Course.all
        end
        
        def new
        end
        
        def create
        course = Course.new(course_params)
        if course.save
        redirect_to "/courses"
        else
        flash[:errors] = course.errors.full_messages
        redirect_to "/courses/new"
        end
        end
        
        def students
        @students = Course.find(params[:id]).students
        end 
        
        def assignments
        @assignments = Course.find(params[:id]).assignments
        end
        
        def edit
        @course = Course.find(params[:id])
        end
        
        def update
        course = Course.find(params[:id])
        if course.update(course_params)
        redirect_to "/courses"
        else
        flash[:errors] = course.errors.full_messages
        redirect_to "/courses/#{course.id}/edit"
        end
        end
        
        def destroy
        @assignments = Course.find(params[:id])
        @assignments.destroy                      //This line is showing me an error
        redirect_to "/courses/new"
        end
        
        private
        def course_params`enter code here`
        params.require(:course).permit(:title, :professor, :room)
        end
        end

My delete function is not working in this code. When I am trying to run this code it shows the following error what is show in the title. please can someone help me to solve this question thank you. I will also highlight the line whatever line shows the error it is just one line. I do not I think it coding thing is right. but, I guess I am missing some inside the code or probably on routes.rb

jeudi 12 novembre 2020

rake aborted when i do rake db:setup

when i do rake db:setup the rake it's aborted and i don't know why...................... because postgresql is running this is the output of postgreql

fabian@Inna-marley:~$ sudo su - postgres [sudo] contraseña para fabian: postgres@Inna-marley:~$ psql psql (13.0 (Ubuntu 13.0-1.pgdg20.04+1)) Digite «help» para obtener ayuda.

postgres=#

this is the output on my terminar

rake db:setup
rake aborted!
ArgumentError: Write key must be initialized
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics/client.rb:319:in `check_write_key!'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics/client.rb:28:in `initialize'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics.rb:14:in `new'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics.rb:14:in `initialize'
/home/fabian/rails-backend/config/initializers/analytics_ruby.rb:3:in `new'
/home/fabian/rails-backend/config/initializers/analytics_ruby.rb:3:in `<main>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:285:in `block in load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:257:in `load_dependency'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:285:in `load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:657:in `block in load_config_initializer'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/notifications.rb:170:in `instrument'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:656:in `load_config_initializer'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:614:in `block (2 levels) in <class:Engine>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:613:in `each'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:613:in `block in <class:Engine>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:32:in `instance_exec'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:32:in `run'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:61:in `block in run_initializers'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:50:in `each'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:50:in `tsort_each_child'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:60:in `run_initializers'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/application.rb:361:in `initialize!'
/home/fabian/rails-backend/config/environment.rb:5:in `<main>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:291:in `block in require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:257:in `load_dependency'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:291:in `require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/application.rb:337:in `require_environment!'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/application.rb:520:in `block in run_tasks_blocks'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bugsnag-6.18.0/lib/bugsnag/integrations/rake.rb:20:in `execute'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/rake-13.0.1/exe/rake:27:in `<top (required)>'
/home/fabian/.rvm/gems/ruby-2.6.6/bin/ruby_executable_hooks:24:in `eval'
/home/fabian/.rvm/gems/ruby-2.6.6/bin/ruby_executable_hooks:24:in `<main>'
Tasks: TOP => db:setup => db:schema:load_if_ruby => db:create => db:load_config => environment
(See full trace by running task with --trace)

Issue with the build for has_one association

I get getting an error every time I try to save a model with a has_one association, and I am not sure what I am doing wrong. Here is the error message and code below enter image description here

user.rb

  has_one :user_options

user_option.rb

 belongs_to(
        :user,
        class_name: 'User',
        foreign_key: 'user_id',
        inverse_of: :user_options
    )

user_options_controller.rb

def create
    @user = current_user
    @user_option = current_user.build_user_option(user_option_params)
    respond_to do |format|
      if @user_option.save
        format.html { redirect_to @user_option, notice: 'User option was successfully created.' }
        format.json { render :show, status: :created, location: @user_option }
      else
        format.html { render :new }
        format.json { render json: @user_option.errors, status: :unprocessable_entity }
      end
    end
  end

Any help would be great!

mercredi 11 novembre 2020

Is it possible to use onchange on base select option

Is there a way to use a submit onchange on this select option. I know I can do it on the <% f.select%> one with :onchange => 'this.form.submit()'), but I can't find any documentation on how to do it on this select statement.

<%= form_for(@profile_option, remote: true) do |form| %>

    <div class="form-group" id="profile_options_budgetid" >
      <div class="h7 text">Select Budget to Show</div>
         <select class="custom-select" name="profile_options[budget_id]" id="profile_options_budgetid">
           <option disabled value="" selected hidden>Please Select</option>
           <% Budget.where(user_id:current_user).each do |budget| %>
           <option value=<%= budget.id %>> Budget: <%= budget.month %> <%= budget.year %>
            </option>
                                            
             <% end %>
         </select>
      </div>
<% end %>

mardi 10 novembre 2020

rake db:seed error- uninitialised constant

I came across the following error when running rake db:seed:

Running via Spring preloader in process 26002 rake aborted! NameError: uninitialized constant Location /mnt/c/Users/raeye/AppData/Local/Packages/CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc/LocalState/rootfs/home/cpde/weatherapp/db/seeds.rb:9:in <main>' -e:1:in ' Tasks: TOP => db:seed (See full trace by running task with --trace)

Seed file:

l = Location.create(name: "New York City")
l.recordings.create(temp: 32, status: "cloudy")
l.recordings.create(temp: 28, status: "rainy")
l.recordings.create(temp: 30, status: "sunny")
l.recordings.create(temp: 31, status: "rainy")

Location:

class Location < ApplicationRecord
  has_many :recordings
end

Recording:

class Recording < ApplicationRecord
  belongs_to :location
end

timestamp files

class CreateLocations < ActiveRecord::Migration[6.0]
  def change
    create_table :locations do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateRecordings < ActiveRecord::Migration[6.0]
  def change
    create_table :recordings do |t|
      t.references :location, null: false, foreign_key: true
      t.integer :temp
      t.string :status

      t.timestamps
    end
  end
end

I'm thinking that it could due to naming convention error, can anyone shed some light on this?

Having trouble using unless current_page? to hide a button

I'm trying to hide this button from all the show pages of the Rooms model. I have an array of the rooms id stored in @extra but whenever I try to use current_page?(room_path(@extra)) it doesn't work, but when I specify the id, for example, current_page?(room_path(6)) it works and hides the button. What am I doing wrong?

<% unless current_page?(controller: 'rooms') || current_page?(room_path(@extra))%>

   <button onclick="myFunction()" class="button btn btn-light bg-white rounded-pill shadow-sm px-4 mb-4" 
   style="vertical-align:middle">
   <span>
      <small class="text-uppercase font-weight-bold"> Nav-bar Toggle</small>
   </span>
</button>

      <% end %>

How do I hide button text with CSS?

I'm trying to hide the text Following when a user hovers over a button. I don't really have too much experience with CSS and am having difficulties doing this.

This is my button

<span>
   <%= link_to  'Following', follow_url(found), method: :delete, 
                class: "btn unfollow-button", id: 'unfollow-button', 
                data: { confirm: 'Are you sure?' } 
    %>
</span>

Below is the application.scss

.unfollow-button {
  width: 100px; /* set a width so it doesnt change upon hover */
  content: 'Following';
  border-color: #bd2b2b;
  background-color: #140d6d;
  color: white;
  margin-left: 20px;
  &:visited, &:focus, &:hover {
    content: 'Following';
    border-color: #FF0000;
    background-color: #FF0000;
    color: white;
  }
  
}
.unfollow-button:hover span {
  display:none
}
.unfollow-button:hover:before {
  content:" Unfollow ";
}

Right now the button is appending the new content Unfollow to the front of the button, but not removing the old content

So the button goes from Following to Unfollow Following instead of the desired result of Following to UnFollow

Any help would be greatly appreciated. Thanks!

dimanche 8 novembre 2020

Can I replace (Date.current - created_at.to_date).to_i <= number_of_days with number_of_days.days.ago.to_date? Is it a good idea?

In my models/book.rb I have this

  def created_since?(number_of_days)
    (Date.current - created_at.to_date).to_i <= number_of_days
  end

That is used in view files like

<% if @book.created_since?(30) %>

Can I optimize it editing with something like this?

  def created_since?(number_of_days)
    number_of_days.days.ago.to_date
  end

Is it a good idea? will it work the same?

samedi 7 novembre 2020

Need a block of ruby code explained - or at least what I need to do to look it up

I'm a programmer, but I don't know ruby and/or ruby on rails at all. All I need to do is skip this validation check - have it return true - or return whatever value it returns if the hash is unique. I can't find explanations for the use of : nor :on Can anyone either explain to me what is happening here, or tell me how I can look up the pertinent symbols/terms?

class Stl < ApplicationRecord
  before_validation :compute_hash
  validates_uniqueness_of :md5hash, :on => :create

  mount_uploader :file, StlUploader
  belongs_to :product


  def compute_hash
    self.md5hash = Digest::MD5.hexdigest(self.file.read)
  end

end

vendredi 6 novembre 2020

How can I scrape a Website with onClick event listener using Nokogiri

I am trying to scrape a website using Nokogiri and download documents thats are posted on the website. I can scrape other websites like this one: Matatiela Website and get the documents from it. But when I try to scrape this website: Mbhashe Website I can't get the documents because I have to first triger the onclick event in order to get to the document.

The problem now, I don't know how to triger the onclick event in order to get to the document. I have tried this code that I worked on with my friend but it didn't work:

if url.include?('http://www.alfredduma.gov.za/bids-tender-notices/')
   file = anchor['onclick'].to_s.gsub("location.href=","").gsub(";return false;","").gsub("'","")
   f = mech.get(file)
   fileNmae = f.header['content-disposition']
   fileNmae = fileNmae.match('"(.*?)"').andand[1].to_s
   fileNmae = municipalityName+ " -" +fileNmae.gsub("_"," ")
   downld(municipalityName,file,filepath,fileNmae,provinceName)
end

This code didn't work. But bellow is the code that is similar to the one i used to scrape Matatiela website but it's not working on the website of Mbhashe. Can you please help me because it does not return anything.

["https://www.mbhashemun.gov.za/procurement/tenders/","div.tb > div.tbrow > a","http://www.mbhashemun.gov.za","Mbhashe municipality","Eastern Cape"]

My Myfuction gets the css from this array.

if baseurl.include?('ttps://www.mbhashemun.gov.za/procurement/tenders/')
              
                            puts "downloading from mbhashemun"
                            parenturl = anchor['href']
                            puts parenturl
                            puts baseurl
                            tenderurl = parenturl
                          begin
                            if tenderurl.include?('http://www.mbhashemun.gov.za/web/2018/11/upgrade-and-maintenance-of-data-centre-for-a-period-of-three-03-years/')
                                   puts "the document is currently not available"
                            else
                                    puts tenderurl
                                    passingparentUrl = HTTParty.get(tenderurl)
                                    parsedparentUrl = Nokogiri::HTML(passingparentUrl)
                                    downloadtenderurl = parsedparentUrl.at_css('div.media div.media-body > div.wpfilebase-attachment > div.wpfilebase-rightcol > div.wpfilebase-filetitle > a')[:href]
                                    puts downloadtenderurl
                                    bean =  downloadtenderurl
                                    puts bean
                                    myfunction =  bean.split('/').last
                                    puts Myfunction
                                    if File.exists?(File.join('public/uploads', Myfunction))
                                       puts "the file exist in upload folder and in the database already"
                                    else
                                       mech.pluggable_parser.default = Mechanize::Download
                                       mech.get(bean).save(File.join('public/uploads', monwai))
                                       Tender.create  municipality_name: municipalityName ,tender_description:Myfunction ,tender_document: Myfunction ,provincename: provinceName
                                    end
                               end
                            rescue Exception => e
                               puts e
                            end
                         end 

The code supposed to go throught the website and download the documents and save them on the public/uploads folder on the app.

Rails self reference one model with has_many

We want to achieve the following:

  1. Be able to compare 'Projects' with other (multiple) Projects.
  2. Save the comparison reference in the database.

In the past we did this by storing an array in the database like below:

t.string "comparisons", default: [], array: true

Now we are thinking about using another table - unless there is a better way?

Ideally something like this:

We already have this table:

|  projects |
|-----------|
| id | name |
| 1  | abc  |
| 2  | def  |
| 3  | ggg  |
| 4  | fff  |

We want to create another table similar to this:

|       project_comparisons     |
|-------------------------------|
| id | project_id | compared_id |
| 1  |     1      |      2      |
| 2  |     1      |      4      |
| 3  |     2      |      3      |
| 4  |     2      |      4      |

Where in the end we could do something like this:

Project.find(1).project_comparisons.each do |x|
  x.name
end

# Output:
'def'
'fff'

But we are getting lost in the relationship setup.

This is what we have so far:

rails g model ProjectComparison project:references compared:references

# Migration file (edited)
create_table :project_comparisons do |t|
  t.references :project, foreign_key: true
  t.references :compared
end


class Project
  has_many :project_comparisons
  has_many :projects, through: :project_comparisons
  # ... Here I think we need something in the line above?
end


class ProjectComparison
  belongs_to :project
end

This now has the the incorrect output. If we now iterate the example:

Project.find(1).project_comparisons.each do |x|
  x.name
end

# Output:
# aaa
# aaa

It should have been 'def' and 'fff'

Can I somehow specify that we want the 'compared_id' to get the correct Project, or are we on the wrong path here?

RSpec test module location

I am new to RSpec and I saw that in the sample the class tested is located in the lib folder. when 'require' class, it can directly import?(that is how I took it) the class from that folder. I tried require app/controllers/the_file_with_the_class_I_want_to_test and it says that it was not found. Should I copy and paste the file into the lib path?

lundi 2 novembre 2020

trying to solve /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError) led to bad interpreter: /usr/local/opt/python/bin/python2.7

  1. After a brew upgrade, I couldn’t run any of my Ruby on Rails apps anymore. I got this error message:

    : dlopen(/Users/ll/.rbenv/versions/2.6.2/lib/ruby/2.6.0/x86_64-darwin18/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError) Referenced from: /Users/ll/.rbenv/versions/2.6.2/lib/ruby/2.6.0/x86_64-darwin18/openssl.bundle Reason: image not found - /Users/ll/.rbenv/versions/2.6.2/lib/ruby/2.6.0/x86_64-darwin18/openssl.bundle

  2. So I tried

brew switch openssl 1.0.2t

solution sugests here https://stackoverflow.com/a/59184347/11410556 But couldn't find openssl 1.0.2t, my version was openssl@1.1 1.1.1h

  1. Then I tried

brew uninstall --ignore-dependencies openssl brew tap-new $USER/old-openssl brew extract --version=1.0.2t openssl $USER/old-openssl brew install openssl@1.0.2t ln -s /usr/local/Cellar/openssl@1.0.2t/1.0.2t /usr/local/opt/openssl

suggest here: https://stackoverflow.com/a/64479513/11410556. But when I ran

brew switch openssl 1.0.2t

I got this Error:

openssl does not have a version “1.0.2t” in the Cellar.
openssl’s installed versions
  1. So I went for this solution

    brew unlink openssl@1.1 brew link openssl@1.0.2t

And then get:

Warning: Refusing to link macOS provided/shadowed software: openssl@1.0.2t
If you need to have openssl@1.0.2t first in your PATH run:
 echo ‘export PATH=“/usr/local/opt/openssl@1.0.2t/bin:$PATH”’ >> ~/.zshrc
For compilers to find openssl@1.0.2t you may need to set:
 export LDFLAGS=“-L/usr/local/opt/openssl@1.0.2t/lib”
 export CPPFLAGS=“-I/usr/local/opt/openssl@1.0.2t/include”
For pkg-config to find openssl@1.0.2t you may need to set:
 export PKG_CONFIG_PATH=“/usr/local/opt/openssl@1.0.2t/lib/pkgconfig”  
  1. I ran the first choice :

    echo 'export PATH="/usr/local/opt/openssl@1.0.2t/bin:$PATH"' >> ~/.zshrc

restart my server and now I have

omz_urlencode:2: /usr/local/bin/pygmentize: bad interpreter: /usr/local/opt/python/bin/python2.7: no such file or directory (edited) 

Whatever I do.

  1. I'm not used to try things I don't understand and I think I went too far. I would be very grateful for any help to get out of this mess.

dimanche 1 novembre 2020

Error while installing ruby on rails asking zeitwork i do no how to proceed with this error

The error message while installing rails please help me to sort it out to learn ruby on rails

How to stop select statement from overwriting the other if they save to the same column

so I am trying to save one of these select statements depending on another select. I have both of these select statements hidden and if the previous select option is 1 goals is shown. If 2 is selected the budget is shown. But the problem is when I try to set the next value. The last select value overwrites the other. So if I select goals and try to save that value the budget select will overwrite it. What is the best way to stop this from happening?

<div class="form-group" id="goal_attachid" style="display: none;">
<%= form.label :"Select Goal to Attach" %>
   <select name="post[attachid]" id="goal_attachid">
    <option disabled value="" selected hidden>Please Select</option>
    <% Goal.where(user_id:current_user).each do |goal| %>
       <option value=<%= goal.id %>> Goal: <%= goal.title %></option>
    <% end %>
   </select>
  </div>

    <div class="form-group" id="budget_attachid" style="display: none;">
       <%= form.label :"Select Budget to Attach" %>
       <select name="post[attachid]" id="budget_attachid">
        <option disabled value="" selected hidden>Please Select</option>
        <% Budget.where(user_id:current_user).each do |budget| %>
           <option value=<%= budget.id %>> Budget: <%= budget.month %> <%= budget.year %>
        </option>
       <% end %>
  </select>
</div>