lundi 24 août 2020

How to fill in the AWS data for storage.yml

I want to push a Ruby on Rails app to heroku. But it gets stuck.

remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
remote:        Some gems seem to be missing from your vendor/cache directory.
remote:        Could not find aws-eventstream-1.1.0 in any of the sources
remote:        Bundler Output: Some gems seem to be missing from your vendor/cache directory.
remote:        Could not find aws-eventstream-1.1.0 in any of the sources
remote:
remote:  !
remote:  !     Failed to install gems via Bundler.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to pure-crag-52432.
remote:
To https://git.heroku.com/pure-crag-52432.git
 ! [remote rejected] user-microposts -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/pure-crag-52432.git'

No I am not sure in how to fill in field below for the storage.yml as given in this guide: .

amazon:
  service: S3
  access_key_id:     <%= ENV['AWS_ACCESS_KEY_ID'] %>
  secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
  region:            <%= ENV['AWS_REGION'] %>
  bucket:            <%= ENV['AWS_BUCKET'] %>

Should I just leave it as it is and will the heroku configuration automatically be linked to this file?

I tried this (of course I changed all the answers a bit):

amazon:
  service: S3
  access_key_id:     AKIAXOOFZZFFKMQD3CFD
  secret_access_key: Cj8BcL452tDer5ryTPBRlan5LHOq76WXgvTDHmvc
  region:            region=eu-east-3
  bucket:            rails-tutorial-joost

These are my Heroku configurations:

➜  sample_app git:(user-microposts) heroku config
 ›   Warning: heroku update available from 7.42.2 to 7.42.6.
=== pure-crag-52432 Config Vars
AWS_ACCESS_KEY_ID:        AKIAXOOFOGFKKMQD3CFE
AWS_BUCKET:               rails-tutorial-joost
AWS_REGION:               region=eu-east-3
AWS_SECRET_ACCESS_KEY:    Ci8BcL452tcxDer5ryTPBRlan5LHOq76WXgvTDHmvc
DATABASE_URL:             postgres://blohftwliwefcg:6cfd2ccz2cc27301f86a1fe3c4686bb77784e67a62312d55c7e5751dfd61331c156@ec2-34-192-173-173.compute-1.amazonaws.com:5432/davr7msm9qlqh1
LANG:                     en_US.UTF-8
RACK_ENV:                 production
RAILS_ENV:                production
RAILS_LOG_TO_STDOUT:      enabled
RAILS_MASTER_KEY:         ./config/credentials/production.key
RAILS_SERVE_STATIC_FILES: enabled
SECRET_KEY_BASE:          32c6c8d057cc6c61071f18429e64zxczxc337d795bfa81abd04ed3e74377eff9e6cddb024967e6a0ffb9bc7de55b408ad71291ab5e518bcfe20bb5a7b44871d570cc61
SENDGRID_PASSWORD:        bdsk6q67625964
SENDGRID_USERNAME:        appasd6786712@heroku.com

jeudi 20 août 2020

How to validate error message before update in ruby on rails

I got the error message before save. But I can't validate the error messages before update.

      def create
        # @student = Student.new
        @student = Student.new(student_params)
        
        # @student = @student.school.build(student_params)
        if @student.valid?
          @student.save
            redirect_to students_path
            # render 'new'
        else
            render 'new'
        end
      end
    
      def edit
        @schools = School.all
        @student = Student.find(params[:id])
      end
    
      def update
        @student = Student.find(params[:id])
         if @student.valid?
          @student.update(student_params)
            redirect_to students_path
        else
          render 'edit'
        end
      end

def student_params params.require(:student).permit(:status, :email, :password, :school_id, :department_id)

end

Adding values to array hash ruby at a specific postion

I have a hash response from a JAVA service which looks like this :

jsonResponse = {:json=>{"reply"=>[{"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "score"=>"1"}, {"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "score"=>"2"},{"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "score"=>"3"}]}, :status=>200}

I have to add one key value pair at a specific position to each of these reply array objects, so that the response transforms to something like this , to make it simpler for now, lets try adding a samke key value pair at a particular position:

jsonResponse = {:json=>{"reply"=>[{"person"=>"abc", "roll_no"=>"1234","location"=>"loc1", "new_value => "new_result", "score"=>"1"}, {"person"=>"def", "roll_no"=>"1235", "location"=>"loc2","new_value => "new_result", "score"=>"2"},{"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "new_value => "new_result", "score"=>"3"}]}, :status=>200}

This is what I have tried ,I run .each through jsonResponse :

jsonResponse[:json]['reply'].each do |object|
               objectArray = object.to_a
               insert_at = objectArray.index(objectArray.assoc('score'))
               object = Hash[objectArray.insert(insert_at, ['new_value','new_result'])]
               print("\n\nTest\n\n")
               print object
      end
    print("\n\nFinal Response\n\n")
    print jsonResponse

The object which i am printing has the desired response but it does not get updated in the jsonResponse

This is the output of the above code snippet:


Test

{"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "new_value"=>"new_result", "score"=>"1"}

Test

{"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "new_value"=>"new_result", "score"=>"2"}

Test

{"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "new_value"=>"new_result", "score"=>"3"}

Final Response

{:json=>{"reply"=>[{"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "score"=>"1"}, {"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "score"=>"2"}, {"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "score"=>"3"}]}, :status=>200}

mercredi 19 août 2020

How to get data from database with specific combination of name

I am working on ruby on rails project and I need to get data from the database with a specific combination like c*_c*_othername * can be numbered 1,2,3 etc like c1_c1_anystring. Prefix c is fixed for all time. I am trying with following code but it's not working

Topic.where("name like ?", "%c*_c*_*%")

mardi 18 août 2020

Heroku: upgrading Ruby application from Cedar-14 to Heroku-18

I am working on upgrading the heroku stack of my Ruby application from Cedar-18 to Heroku-18. The Ruby version of my application is 2.0.0 however the Heroku-18 stack is based on Ubuntu 18.04 requires a higher version of Ruby. As my application uses an older version, upgrading is complex and time consuming. With that said,

  1. Can I still be able to run with the same older versions of Ruby, Ruby Gems and Rails on Heroku-18 stack at my own RISK? As I am still be able to run my application locally on Ubuntu 18.04
  2. Does heroku supports SSH to servers for installation of older versions and related plugins like AWS?

lundi 17 août 2020

How to set a random number before_save for a model?

I have a Produt model, that if the user left blank, I need to generate a random number. How can I achieve that?

  def self.set_random_number()
   if self.code == null
    self.code.rand(1000..99999)
   end
  end

I tried this method, and called before_save :set_random_number(). But it doesn't work. Could you guys please help me?

samedi 15 août 2020

Need a linechart hash (chartkick) (sql query) to get the count of total number records till this month and grouped by month

I have a table of records which need to be visualized on chartkick and the visualization must be as follows:

June -> Total records created = 1

July -> Total records created = June records + July records

August -> Total records created = June + July + August records.

...and soon

mardi 11 août 2020

Modify Form Data before submitting in Rails Application

I have a form, where there are some fields and input[file] element. I'm using Cropper.js to crop the image. The issue I'm facing here is file input has the original image, but I have no way append the new cropped image to the form data before the form is submitted.

const readURL = function (input, target, preview, form_id) {
 let image = document.querySelector(preview);
 let file = document.querySelector(input).files[0];
 let cropper_canvas, imgSrc, reader, imgFile;
 if (file) {
  reader = new FileReader();
  reader.onload = (e) => {
   image.src = e.target.result;
   cropper_canvas = new Cropper(image);
  };
  reader.readAsDataURL(file);
 }

 $("#crop-button").click((e) => {
  imgSrc = cropper_canvas.getCroppedCanvas({ width: 300 }).toDataURL();
  cropper_canvas.getCroppedCanvas({ width: 300 }).toBlob(function(blob){
   imgFile = blob;
  });
  $(target).css("background-image", imgSrc);
  $(target).attr("style", `background-image: url(${imgSrc})`);

  $(`#edit_counselor_${form_id}`).submit(function () {
    var formData = new FormData(document.querySelector(`#edit_counselor_${form_id}`))
    formData.append("counselor[profile_image]", imgFile);
    return true;
  });
 });
};

lundi 10 août 2020

Style/ConditionalAssignment: Use the return of the conditional for variable assignment and comparison

Below is my Ruby on Rails code -

inactive_list = [1,2,3,4,5]
raw_data = []

data = {
  name: "Test",
  full_name: "Test data"
}
if inactive_list.include? <<id of data>>
  data[:active] = false
else
  data[:active] = true
end

raw_data << data

I am getting Rubocop linting error for if...else statement. I tried making several changes but unable to fix linting Rubocop error.

C: Style/ConditionalAssignment: Use the return of the conditional for variable assignment and comparison.

Please help! Thanks in advance!

samedi 8 août 2020

Updating RVM, Ruby, and Rails on macOS

I'm using macOS in development (Ubuntu in prod), and want to update things for my next project. But I keep running into issues:


$ rvm -v
rvm 1.28.0 (latest) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]

$ ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16]

$ brew -v
Homebrew 2.4.9
Homebrew/homebrew-core (git revision 50be1b; last commit 2020-08-08)
Homebrew/homebrew-cask (git revision ccae745; last commit 2020-08-08)

$ rails -v
Rails 5.1.6.1

if I turn on auto-update rvm

I cannot get past the first step in updating rvm

$ rvm install 2.6.1
Found old RVM 1.28.0 - updating.
Downloading https://get.rvm.io
Downloading https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer.asc
Verifying /Users/edmund/.rvm/archives/rvm-installer.asc
gpg: Signature made Wed Jul 24 05:59:45 2019 HKT using RSA key ID 39499BDB
gpg: Can't check signature: No public key
Warning, RVM 1.26.0 introduces signed releases and automated check of signatures when GPG software found.
Assuming you trust Michal Papis import the mpapis public key (downloading the signatures).

GPG signature verification failed for '/Users/edmund/.rvm/archives/rvm-installer' - 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer.asc'!
try downloading the signatures:

    gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

or if it fails:

    command curl -sSL https://rvm.io/mpapis.asc | gpg2 --import -

the key can be compared with:

    https://rvm.io/mpapis.asc
    https://keybase.io/mpapis

And when I follow instructions:

$ gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
gpg: requesting key D39DC0E3 from hkp server keys.gnupg.net
gpg: unable to execute program `/usr/local/Cellar/gnupg2/2.0.30_3/libexec/gpg2keys_curl': No such file or directory
gpg: no handler for keyserver scheme `hkp'
gpg: keyserver receive failed: Keyserver error

following the "if it fails" instruction doesn't seem to raise errors but do not help the problem

command curl -sSL https://rvm.io/mpapis.asc | gpg2 --import -
gpg: key D39DC0E3: "Michal Papis (RVM signing) <mpapis@gmail.com>" not changed
gpg: Total number processed: 1
gpg:              unchanged: 1

Am I missing something obvious?

If I turn off auto-update rvm

$ rvm install 2.6.1
Warning, new version of rvm available '1.29.10-next', you are using older version '1.28.0'.
You can disable this warning with:    echo rvm_autoupdate_flag=0 >> ~/.rvmrc
You can enable  auto-update  with:    echo rvm_autoupdate_flag=2 >> ~/.rvmrc
Searching for binary rubies, this might take some time.
Found remote file https://rubies.travis-ci.org/osx/10.15/x86_64/ruby-2.6.1.tar.bz2
Checking requirements for osx.
Installing requirements for osx.
Updating system....
Installing required custom packages: homebrew/dupes homebrew/dupes.
Error running 'requirements_osx_brew_install_custom homebrew/dupes homebrew/dupes',
showing last 15 lines of /Users/edmund/.rvm/log/1596893890_ruby-2.6.1/install_custom.log
    do
        brew tap "${__tap}" || return $?;
    done
}
current path: /Users/edmund/Documents/playground/ugdev
GEM_HOME=/Users/edmund/.rvm/gems/ruby-2.4.0
PATH=/Users/edmund/.rvm/gems/ruby-2.4.0/bin:/Users/edmund/.rvm/gems/ruby-2.4.0@global/bin:/Users/edmund/.rvm/rubies/ruby-2.4.0/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Users/edmund/.rvm/bin
GEM_PATH=/Users/edmund/.rvm/gems/ruby-2.4.0:/Users/edmund/.rvm/gems/ruby-2.4.0@global
command(3): requirements_osx_brew_install_custom homebrew/dupes homebrew/dupes
++ typeset __tap
++ for __tap in '"$@"'
++ brew tap homebrew/dupes
Updating Homebrew...
Error: homebrew/dupes was deprecated. This tap is now empty as all its formulae were migrated.
++ return 1
Requirements installation failed with status: 1.

Already updated brew by the way...

Any clues?

jeudi 6 août 2020

ASSIST WITH RUBY CODE TO GET "user", "domain" and "domain.com" from email string user@domain.com

please i need help with sumthing like substring of php for ruby that can make me get "user" "domain" and "domain.com" in this output email "user@domain.com"

e.g john@dortmund.com

let say i have %3% in my line of code to call user the result will be = "john"

let say i have %2% in my line of code to call domainname the result will be = "dortmund"

let say i have %1% in my line of code to call domain.com the result will be = "dortmund.com"

i have been cracking my head but couldn't get it.

thank you.

lundi 3 août 2020

How to call Select_tag in Create action in a model

Actually im getting my category model values from category to take input..... category_id act as a foreign key in Product Model I am taking input like this

<%= select_tag 'category', options_for_select(Category.pluck(:name, :id)), class: 'form-control', id: 'sel1' %>

And Pass Category Id in Product_controller Create action like this

def create
@product = Product.new(product_params)
@product.user = current_user

  private

def product_params
  params.require(:product).permit(:productname, :productprice, :productstatus,:image ,:category )
end

But when I create My product An error occurs that category Should be Present. I think that params[:category] not pass the category_id