jeudi 29 avril 2021

You've tried to invoke Spring when it's already loaded (i.e. the Spring constant is defined)

This is probably because you generated binstubs with Spring 1.0, and you now have a Spring version > 1.0 on your system. To solve this, upgrade your bundle to the latest Spring version and then run bundle exec spring binstub --all to regenerate your binstubs. This is a one-time step necessary to upgrade from 1.0 to 1.1.

Here's the backtrace:

/Users/m/Image-Classifier/vendor/bundle/ruby/2.7.0/gems/spring-2.1.1/lib/spring/binstub.rb:11:in load' /Users/m/Image-Classifier/vendor/bundle/ruby/2.7.0/gems/spring-2.1.1/lib/spring/binstub.rb:11:in <top (required)>' /Users/m/.rvm/rubies/ruby-2.7.1/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:92:in require' /Users/m/.rvm/rubies/ruby-2.7.1/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:92:in require' /Users/m/Image-Classifier/bin/spring:15:in <top (required)>' /Users/m/Image-Classifier/bin/rails:3:in load' /Users/m/Image-Classifier/bin/rails:3:in `'

I try with Spring and middleware conflict? but don't worked

to show first the comment left by the current_user using ORDER BY CASE

Into the pages where I show the comments I noted that the previous developer used this system (very good and it works perfectly)

in comments_controller.rb there is this

  def index
    @comments = movie.comments.roots.latest
                    .includes(:user).page(params[:page])
  end

in views/comments/index.html.erb there is this

The Comments
<div id="commentsContainer">
    <%= render partial: 'comment', collection: @comments %>
    <%= paginate @comments %>
</div>

and in view/comments/comment.html.erb there is this

<div id=<%= dom_id(comment) %>>
    <!-- Author -->
    <%= link_to comment.username, user_path(comment.username) %>
    <!-- Body Comment -->
    <%== parse_markdown(comment.text) %>
</div>

Now are showing the latest comments first.

I have to edit it to show first the comment left by the user (logged) that is watching the page and then the latest comments

So I should check if there is a comment left by the current_user and then to show it first. Should I use order by case? how to do?

how can i use .verify in verifying jwt token instead of .decode method in rails?

    def self.decode(token)
    decoded = JWT.decode(token, SECRET_KEY, true)
    HashWithIndifferentAccess.new decoded
    end

I am using the .decode method here to decode the key, when I use .verify instead of .decode it gives me an "undefined method 'verify'" error.

mardi 27 avril 2021

Pros and cons of a Hash vs a table

I am creating an application where I match mentees to mentors based on the mentee's major and the mentor's occupation. I am debating if I should have a hash that maps majors to occupations or if I should store this information in a table in the database. It is a many to many relationship. I would appreciate any feed back on the pros and cons of each data structure. Thank you so much.

jeudi 22 avril 2021

How to find url using controller and action of aliased route

I can find the URLs of most routes using url_for as below

url_for(controller: 'main', action: 'index')

But some of the routes in my application are aliased as

resources :car_insurance_leads, :path=>'car-insurance'

So when I try to find the URL for such a route using

url_for(controller: 'car_insurance_leads', action: 'index')

It gives me incorrect route /blog?controller=car_insurance_leads&action=index

Is there a way to find the URL for aliased routes in Rails 3?

mercredi 21 avril 2021

Rails schema dump says method_missing_with_paginate

I've got a Rails app I've updated to 3.1. I'm trying to run for the first time. So I'm attempting to build the database schema for the first time.

But I'm getting this error "method_missing_with_paginate" for class "Class"...

fonso@mybox:~/my-dev$ rake db:schema:dump
/home/fonso/fgdb-dev/vendor/soap4r/xsd/iconvcharset.rb:9:in `<top (required)>': iconv will be deprecated in the future, use String#encode instead.
DEPRECATION WARNING: ActiveRecord::Associations::AssociationCollection is deprecated! Use ActiveRecord::Associations::CollectionProxy instead. (called from <top (required)> at /home/fonso/fgdb-dev/config/application.rb:16)
DEPRECATION WARNING: ActiveRecord::Associations::AssociationCollection is deprecated! Use ActiveRecord::Associations::CollectionProxy instead. (called from <top (required)> at /home/fonso/fgdb-dev/config/application.rb:16)
rake aborted!
NameError: undefined method `method_missing_with_paginate' for class `Class'
/home/fonso/fgdb-dev/config/application.rb:16:in `<top (required)>'
/home/fonso/fgdb-dev/Rakefile:4:in `<top (required)>'
(See full trace by running task with --trace)

Here is my gemfile

source 'http://rubygems.org'

gem 'rails', '3.1.0'

gem 'pg', '~> 0.10.1pre209'


gem 'will_paginate', '~> 2.3.17'
gem 'soap4r-middleware', '~> 0.8.6'
gem 'soap4r',  '~> 1.5.6'
gem 'prawn-labels', '~> 0.11.3.0'
gem 'nokogiri-plist', '~> 0.3.0'
gem 'rails_sql_views', '~> 0.8.0' #all versions (0.1.0 - 0.8.0)of this crap require ruby 2.3. we can not use 2.3
gem 'prototype_legacy_helper', '0.0.0', :git => 'https://github.com/rails/prototype_legacy_helper.git'

# config.gem 'pg', '~> 0.20.0'
# pg 0.20.0 may be the version needed to overcome the t.tgisconstraint error. Only works with ruby 2.0
# can we use this..https://rubygems.org/gems/postgres-pr ??

"method_missing_with_paginate" makes me think this has something to do with will_paginate.

Can anyone point me in the right direction on fixing this?

How can I prevent SQL injection in following rails query?

Data is a param in the below statement :

condition = params["id"].present? ? "employers.status = '#{params["id"].upcase}' and employers.task = '#{data.upcase}'" : "employers.task.rdu = '#{data.upcase}'"

samedi 17 avril 2021

Why does it say bundler not installed after i install bundler?

I have rbenv and a few rubies installed. On my 1.9.3-p484 i'm trying to install bundler. I seem to install it....but it does not show up. I get this error...

fonso@mybox:~/my-dev$ gem install bundler -v '1.0.22'
Successfully installed bundler-1.0.22
1 gem installed
Installing ri documentation for bundler-1.0.22...
Installing RDoc documentation for bundler-1.0.22...
fonso@mybox:~/my-dev$ bundler --version
rbenv: bundler: command not found

The `bundler' command exists in these Ruby versions:
  2.3.0
  2.4.4
  2.5.8

fonso@mybox:~/my-dev$

How can I fix this?

Rails seed not populating data for one of the models

I am new to rails and trying to pass on some data in seeds.rb but doesn't show up when I do rails c. I am trying to add reviews for an airline but the count shows up as 0 instead of 2. So it doesn't seem to be adding the reviews for the first airline somehow.

seeds.rb

airlines = Airline.create([{ name: "Air New Zealand", image_url: "url.com" },
                           { name: "Jetstar", image_url: "https://www.jetstar.com/_/media/images/global/logos/jetstar-logo-black_svg.svg?la=en-NZ&hash=E2F625C27A6B66D3D129B3FB327F700503B14D7E" }])

reviews = Review.create([
  { title: "Good service", description: "service was good", score: 4, airline: airlines.first },
  { title: "Poor service", description: "service was poor", score: 2, airline: airlines.first },
])

schema.rb

ActiveRecord::Schema.define(version: 2021_04_17_115814) do

  create_table "airlines", force: :cascade do |t|
    t.string "name"
    t.string "image_url"
    t.string "slug"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "reviews", force: :cascade do |t|
    t.string "title"
    t.string "description"
    t.integer "score"
    t.integer "airline_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["airline_id"], name: "index_reviews_on_airline_id"
  end

  add_foreign_key "reviews", "airlines"
end

airline.rb

    class Airline < ApplicationRecord
  has_many :reviews
  before_create :create_slug, :calculate_score

  #create a slug like 'url.com/air-new-zealand' for an airline
  def create_slug
    self.slug = name.to_s.parameterize
  end

  def calculate_score
    reviews.average(:score).to_f.round(2) * 100
  end
end

review.rb

class Review < ApplicationRecord
  belongs_to :airline
end

vendredi 16 avril 2021

Rails not updating record when passed an array of association ids

Am I correct in saying that Rails will handle adding associated has_many items to an object if you pass the params in with a definition like tag_ids as an array of ids?

If so, I'm posting the following to my Item controller:-

{
    "title": "Bottle",
    "tag_ids": [25, 26]
}

What's happening is that the tag_ids are being ignored. I already added tag with id 25, but 26 isn't being included.

My controller:-

# PATCH/PUT /api/items/1
  def update
    if @item.update(item_params)
      render json: @item, include: ['tags']
    else
       render json: @item.errors
    end
  end 

  def item_params
    params.require(:item).permit(:name, :tag_ids)
  end

Item has_and_belongs_to_many Tags, and they have a join table of jobs_tags. The association works because I get Tags returned in my response above. I can't seem to add them however. Any idea where I may be going wrong?

Do I need to explicitly add a tag_ids field to the Item model?

jeudi 15 avril 2021

Error while running bundle exec rake db:create couldn't create database in rails 3

bundle exec rake db:create NOTE: Gem::Specification#has_rdoc= is deprecated with no replacement. It will be removed on or after 2018-12-01. Gem::Specification#has_rdoc= called from /Users/priyanka/Documents/GitHub/helpkit/vendor/gems/delayed_job/delayed_job.gemspec:17. You are setting a key that conflicts with a built-in method OmniAuth::AuthHash::InfoHash#name defined at /Users/priyanka/.rvm/gems/ruby-2.3.8/gems/omniauth-1.3.2/lib/omniauth/auth_hash.rb:34. This can cause unexpected behavior when accessing the key as a property. You can still access the key via the #[] method. You are setting a key that conflicts with a built-in method OmniAuth::Strategy::Options#store defined in Hash. This can cause unexpected behavior when accessing the key as a property. You can still access the key via the #[] method. Called 'load_file' without the :safe option -- defaulting to safe mode. You can avoid this warning in the future by setting the SafeYAML::OPTIONS[:default_mode] option (to :safe or :unsafe). /Users/priyanka/Documents/GitHub/helpkit/lib/omniauth/strategies/google_oauth2.rb:6: warning: already initialized constant OmniAuth::Strategies::GoogleOauth2::DEFAULT_SCOPE /Users/priyanka/.rvm/gems/ruby-2.3.8/gems/omniauth-google-oauth2-0.1.13/lib/omniauth/strategies/google_oauth2.rb:8: warning: previous definition of DEFAULT_SCOPE was here [mysql_127.0.0.1:3306] Can't connect to MySQL server on '127.0.0.1' (61) Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "database"=>"helpkit1", "pool"=>5, "host"=>"127.0.0.1", "username"=>"root", "password"=>nil, "reconnect"=>true, "semian"=>{"enable"=>false, "success_threshold"=>3, "error_threshold"=>3, "error_timeout"=>20, "bulkhead"=>false, "dryrun"=>false}, "shard_names"=>["shard_1", "sandbox_shard_1"]}, charset: utf8, collation: utf8_unicode_ci (if you set the charset manually, make sure you have a matching collation) [mysql_127.0.0.1:3306] Can't connect to MySQL server on '127.0.0.1' (61) Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "database"=>"helpkit_test_rails3", "host"=>"127.0.0.1", "username"=>"root", "password"=>nil, "reconnect"=>true, "semian"=>{"enable"=>false, "success_threshold"=>3, "error_threshold"=>3, "error_timeout"=>20, "bulkhead"=>false, "dryrun"=>false}, "shard_names"=>["shard_1"]}, charset: utf8, collation: utf8_unicode_ci (if you set the charset manually, make sure you have a matching collation)

How to store in mongodb crawled/scrapped data with nokogiri?

Hello I'm trying to save to a database (mongodb) some data that that I'm crawling using nokogiri I have the model of the table that I want to store the data, the model of the crawler, but I'm clueless in how to save the data into mongodb, I'm not using AR since it doesn't seem to support mongo.

Error: your ruby version is 3.0.0 but your Gemfile specified 2.4.2

I need to work on ruby 3.0.0. How can i update my gemfiles?

mardi 13 avril 2021

Ruby | How to convert mail like numbers?

I have an exercise where I have to make a program to program an email list from 1 to 50 in this format "jean.dupont.01@email.fr"

I have tried several methods, and I think I have found the right one, but it only converts the numbers. In the result obtained in the terminal I get the email address and the numbers in the array from 1 to 50. I would like this to display the mails 1 by 1 with the numbers changing, thank you in advance.

a = (1..50).to_a

puts "jean.dupont.#{a}@email.fr"

lundi 12 avril 2021

Problem with my program with ruby, i don't understand

puts "Quel âge tu as ?"

print ">"

age = gets.chomp.to_i
i = 0

    
while age > 0 

    

    puts "Il y a " + age.to_s + " ans" + " tu avais : " + i.to_s + " ans"
    age -= 1
    i += 1 

    break if age = i
    puts "Il y a " + age.to_s + " ans" + " tu avais la moitié de ton âge !"
    age = i
end
    

I have a problem with my program on Ruby On Rails. I apologize in advance for my English.

I train on this language by doing an exercise that allows you to enter your age, and to see how old you are in a given year.

But for example. When we reach half our age, for example 20 years old I want to display (in french)

"Ten years ago, you were half your age!"

that I wanted to put thanks to the "break if", but that produces only one line of code. I hope you have understood otherwise do not hesitate to ask for clarification.

Thank you in advance.

dimanche 11 avril 2021

How do I pass parameters from veiws to controller in Ruby through routing in routes.rb?

I am working on a product selling/exchanging project in Ruby where on the homepage you can see all the products up for sell, and exchange. The user who posted the product can be viewed through a link to their profile. But I am having a hard time accessing the database information for each user from the views file. I believe I have to pass the user's ID to the controller to retrieve the data but I am not sure. How can I go about this?

vendredi 9 avril 2021

Redmine OpenID plugin 404

Installed using that instruction github link

All the gems were installed w/o errors but redmine admin console shows 404 when i'm trying to configure this plugin.

Error 404 page in redmine

Don't familiar with ruby at all.

jeudi 8 avril 2021

Else block in Ruby

I just started learning ruby, but there's something I noticed. In JavaScript the else block isn't really needed. So you can do something like

if (condition){
    // do something
  }

//do something else

instead of

if (condition){
    // do something
  } else {
  //do something else
}

is this possible in Ruby ?

mercredi 7 avril 2021

bundle update --conservative devise does not update only "devise" gem

I recently tried to update devise to the latest version specified in the gemfile without affecting its dependencies.

gemfile.lock:

devise (3.5.3)
      bcrypt (~> 3.0)
      orm_adapter (~> 0.1)
      railties (>= 3.2.6, < 5)
      responders
      thread_safe (~> 0.1)
      warden (~> 1.2.3)
thread_safe (0.3.5)
warden (1.2.4)

After I run bundle update --conservative devise i got:

gemfile.lock:

devise (3.6.3)
      bcrypt (~> 3.0)
      orm_adapter (~> 0.1)
      railties (>= 3.2.6, < 5)
      responders
      thread_safe (~> 0.1)
      warden (~> 1.2.3)
thread_safe (0.3.6)    ---> changed from 0.3.5 to 0.3.6
warden (1.2.7)         ---> changed from 1.2.4 to 1.2.7

I am aware that only "devise" gem version changed and not the dependencies but the gems that changed their verions too like thread_safe and warder are also part of the dependencies of devise but out of the scope. What do they rapresent and why have changed their versions?