lundi 27 février 2023

NoMethodError: undefined method `pluck' for nil:NilClass

I am currently working with Ruby on Rails and I encountered a weird thing.

So, I am creating an array, then using .pluck(:client_id) on that array and I get the following error: NoMethodError: undefined method 'pluck' for nil:NilClass.

I used binding.pry to check if the array is indeed nil, but this is the result:


    49: def get_associations(records, tuples)
 => 50:   binding.pry
    51:   ClientAssociatedLocation.with_deleted.
    52:     where(client_id: records.pluck(:client_id)).
    53:     where("CONCAT_WS('-', client_id, location_id) IN (?)", tuples)
    54: end

[1] pry(#<AssociatedLocations::SourcesCreator>)> records
=> [{:id=>nil, :user_id=>nil, :client_id=>1523, :location_id=>2257, :association_type=>"manual"}]
[2] pry(#<AssociatedLocations::SourcesCreator>)> records.pluck(:client_id)
=> [1523]
[3] pry(#<AssociatedLocations::SourcesCreator>)>

As you can see, the records is clearly not nil and the pluck works. Do you have any idea of why this occurred?

samedi 25 février 2023

"rails db:migrate" problem : unexpected : at the code and give the suggest "why on earth is this"?

I coded a very simple rails program and ran the code

rails db:migrate

to make the database, but it gave me this error

rails aborted!SyntaxError:/Users/xxx/Desktop/Rails/Addcustomfieldstousermodel/db/migrate/20230218102843_add_columns_to_user.rb:7: syntax error, unexpected ',', expecting '.' or &. or :: or '['
  t.boolean, :status, default: false # why on eart...
                    ^
  Tasks: TOP => db:migrate
 (See full trace by running task with --trace)

I do not know why it gave me this error ? Because I think my code is right with the grammar ? When I change the code from , to . or & , it still gave me this error again and again ?

Here is my code for your reference.

https://github.com/nguyencuc2586/problem1

Could you please give me some advices ? Thank you in advance.

mardi 21 février 2023

How to convert an object into array of values from object in ruby

If object is- Object Data=Object.to_json() Data looks something like these Data=[{"id":1},{"id":2},{"id":3}]

And I want to transform into an array looks something like that Data=[1,2,3]

lundi 20 février 2023

How can I rewrite the rails to optimize the code without using unnecessary loop

I want to remove the below loop from rails code.

list=Student.find_by_sql("select study_id from students where id in (1,2,3,4,5)") 

list.each do |val|
  Subject.where(:sub_id=>val).update({:sub_code=> 'SO1'})
end

How can I rewrite these code without looping list and directly pass list in where condition?

dimanche 19 février 2023

NoMethodError in Account::Users#edit , how to resolve this error

NoMethodError in Account::Users#edit

%section
    %header
      %h3
        = precede "User Information" do
          - if editable_user.is_federated?(session)
            = link_to "Change Password",main_app.try(:new_password_path)
    .inputs

undefined method `chomp' for nil:NilClass

My Users/edit controllers is

def edit
end

i added function federatedid in my user model by passing session to hide password in the form.html.haml it is giving this error,how to resolve error

I added this function in user.model

def is_federated?(session)
session[:federatedIdHeader].present?
end

My form.html.haml file is this, i am trying to edit the user if it federated by passing the session in 7th line , this is basically in another repo, i am using it as a gem

.user-edit-form
= simple_form_for(editable_user,html: { autocomplete: "off" }) do |f|
%section
  %header
    %h3
      = precede "User Information" do
      -if editable_user.is_federated?(session)
        = link_to "Change Password",main_app.try(:new_password_path)
  .inputs
    = f.input :needs_setup,as: :hidden,input_html: { value: false }
    = f.input :name,required: true
    = f.input :email,disabled: true
    = f.input :phone,label: "Phone Number"
    = f.input :title
- if editable_user_is_authorized?(editable_user)
  %section
    %header
      %h3
        = precede "Company Information" do
          %small (Shared by all users in your company)
    .inputs
      = f.fields_for :account do |a|
        = a.input :name,required: true
        = a.input :url,label: "Web Address",required: true
.actions
  = f.button :submit, "Save Profile", class: "button little green"

i am getting this error while deploying

users/edit/_form.html.haml:7: syntax error, unexpected ')' ));}\n", 0, false);if 
editable_user.is_federated?(session) 

/edit/_form.html.haml:9: syntax error, unexpected ')', expecting keyword_end ));}\n", 0, 
false);end;

How to make it work

vendredi 17 février 2023

Rspec, rails 7 Update_column on date value not updating the record

after im upgrading to rails 7 and ruby 3, I'm facing one issue in rspec.

issue: whenever I'm using the update_column of date field of a column of the model in rspec, it shows the result of the update as true, but that value is not getting updated in the database.

Example:

My model. Dishes

it contains prepared time, and served time as date field: structure.sql file.

CREATE TABLE public.dishes (
          ....
          ....
          prepared_time date, 
          served_time date, 
          ......
)

my rspec

it "should send notification on updating served time" do
      dish.update_column(:prepared_date, (Time.zone.now).strftime('%m/%d/%Y'))
      params['orders'].merge!(served_time: [(Time.zone.now + 
      3.day).strftime('%m/%d/%Y')])
      response = put(:update, params)
      json = JSON.parse(response.body)
      expect(json).to eq(success_response)
end

here after debugging im found that the dish is not updated with prepared_date, as the prepared_date is nil, but when I try to update other fields, they are getting updated.

But the same spec works on rails 4.

what might be the reason??

jeudi 16 février 2023

Ruby code not executing even with code = 0

Here is a link to a google drive with a .docx folder to all my code. Also directions of my assignment I had to create for any confusion on what im making. I am making a water bill. I coded everything but it doesnt execute. Even thoe it has the code=0 prompt in my terminal. I am trying to get it to print the information.

link

I tried to create a main function. Didnt work. Tried to call my function didnt work. Any ideas? again I could be a big goof and messed up my code.

Rails admin gem, polymorphic association

How to get the queried data having polymorphic association

I have an 3 models

class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end```

Employee and Product have column **is_active**.
In rails admin dropdown. I want to display the data where employee and product is **is_active = true.**

Have tried multiple ways to achieve this.
Please let me know if there is any solution?

samedi 11 février 2023

Full-Text Search pdf and word file content using ruby

I am working on a ruby on rails project. we want to develop a feature that can :

  1. upload various pdf, word files into the system
  2. search a keyword among the content and titles among all the files uploaded, and the show matched result.

any known tools and libs can help me do that?

thank you!

jeudi 9 février 2023

How to join zoom meeting in ruby on rails?

I have created a zoom meeting. I want to join this meeting within my rails 7 application. Join Link should not redirect me to any other website.

Is there any gem or something to do this?

dimanche 5 février 2023

rails problem : "connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory ..."?

I am newbie with rails and here is my problem.

I made a very simple rails program and at the first time I ran this program, it worked perfectly.

But at the second time, It gave me this error :

connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory
Is the server running locally and accepting connections on that socket?

As you can see in this picture

my problem

I referenced this stackoverflow's question Rails | connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory And as the answer, I added the 2 lines to the database.yml and ran the command : bundle install

default: &default
...
host: <%= ENV.fetch('DATABASE_HOST', 'localhost') %>
port: <%= ENV.fetch('DATABASE_PORT', 5432) %>

But it gave me another error

Puma caught this error: Cannot load database configuration:
YAML syntax error occurred while parsing 
/Users/xxx/Desktop/Rails/freelancer/config/database.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Error: (<unknown>): mapping values are not allowed in this context at line 90 column 7 (RuntimeError)

So could you please give me some advices to solve this problem ? Here is my program for reference.

https://github.com/nguyencuc2586/freelancer01

Thank you in advance.

samedi 4 février 2023

bulma html does not display as expect even though the code is entered properly

I am newbie with Rails and here is my problem

I created a rails program by this command

rails new freelancer -d=postgresql --javascript=webpack

And I had no problem

I wanted to use bulma extension in my rails program and I added these line to the gemfile

gem 'bulma-rails', '~> 0.9.4'
gem 'bulma-extensions-rails', '~> 1.0.30'

and these lines to the app -> assets -> stylesheets -> application.css

@import 'bulma';
@import 'bulma-extensions';

then I ran these commands

bundle install;
yarn add jquery;

and I had no error.

I created a rails page by this command

rails g controller pages home

and add the bulma code to the app -> views -> layouts -> application.html.erb file

Here is my application.html.erb file

<!DOCTYPE html>
<html>
<head>
<title>Freelancer</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
</head>
<body>
<nav class="navbar" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<a class="navbar-item" href="https://bulma.io">
  <img src="https://bulma.io/images/bulma-logo.png" width="112" height="28">
</a>
<a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample">
  <span aria-hidden="true"></span>
  <span aria-hidden="true"></span>
  <span aria-hidden="true"></span>
</a>
</div>
<div id="navbarBasicExample" class="navbar-menu">
<div class="navbar-start">
  <a class="navbar-item">
    Home
  </a>
  <a class="navbar-item">
    Documentation
  </a>
  <div class="navbar-item has-dropdown is-hoverable">
    <a class="navbar-link">
      More
    </a>
    <div class="navbar-dropdown">
      <a class="navbar-item">
        About
      </a>
      <a class="navbar-item">
        Jobs
      </a>
      <a class="navbar-item">
        Contact
      </a>
      <hr class="navbar-divider">
      <a class="navbar-item">
        Report an issue
      </a>
    </div>
  </div>
</div>
<div class="navbar-end">
  <div class="navbar-item">
    <div class="buttons">
      <a class="button is-primary">
        <strong>Sign up</strong>
      </a>
      <a class="button is-light">
        Log in
      </a>
    </div>
  </div>
</div>
</div>
</nav>
<%= yield %>
</body>
</html>

I thought that my home page must be the design as here

https://bulma.io/documentation/components/navbar/

, but it liked this

my problem

I did not know why it became like this ? Could you please give me some advice for my problem ? Here is my code, if you need for reference

https://github.com/nguyencuc2586/freelancer01

Thank you in advance!

vendredi 3 février 2023

rails did not auto add "jquery" to the package.json and yarn.lock files even though codes have been added to needed files?

I created a very simple Rails program named freelancer and want to use Bulma library and Jquery in this program. So here is what I did.

In the file "Gemfile", I add this lines

gem ‘bulma-rails’, ‘~> 0.9.4’ gem ‘bulma-extensions-rails’, ‘~> 1.0.30’

In this file app -> assets -> stylesheets -> application.css

I added this lines

@import 'bulma'; @import 'bulma-extensions'

Then I ran these commands

Bundle install; Yarn add jquery;

I thought that in these files package.json and yarn.lock, there must be jquery line ? But there are not.

Here is my code, if you need to reference

https://github.com/nguyencuc2586/freelancer02

Could you please give me some advices for this problem ? Thank you in advance.

Ruby pg-1.4.4 Segmentation fault at 0x0000000000000000

I see Segmentation fault at 0x0000000000000000 error when I try to connect to postgresql. I use ruby 2.7.7, Ubuntu 22.04.1 LTS, rails (5.2.6.2)

What is the reason?

/home/vital/.rvm/gems/ruby-2.7.7/gems/pg-1.4.4/lib/pg/connection.rb:626: [BUG] Segmentation fault at 0x0000000000000000
ruby 2.7.7p221 (2022-11-24 revision 168ec2b1e5) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0075 p:---- s:0448 e:000447 CFUNC  :connect_poll
c:0074 p:0551 s:0444 e:000443 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/pg-1.4.4/lib/pg/connection.rb:626
c:0073 p:0343 s:0431 e:000430 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/pg-1.4.4/lib/pg/connection.rb:759
c:0072 p:0007 s:0420 e:000419 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/pg-1.4.4/lib/pg/connection.rb:695
c:0071 p:0019 s:0414 e:000413 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/pg-1.4.4/lib/pg.rb:69
c:0070 p:0014 s:0408 e:000407 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/postgresql_adapter.rb:692
c:0069 p:0027 s:0403 e:000402 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/postgresql_adapter.rb:223
c:0068 p:0012 s:0395 e:000394 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-postgis-adapter-5.2.3/lib/active_record/connection_adapters/postgis_adapter. [FINISH]
c:0067 p:---- s:0387 e:000386 CFUNC  :new
c:0066 p:0110 s:0379 e:000378 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-postgis-adapter-5.2.3/lib/active_record/connection_adapters/postgis/create_c
c:0065 p:0021 s:0372 e:000371 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:83
c:0064 p:0021 s:0368 e:000367 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:87
c:0063 p:0014 s:0364 e:000363 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:85
c:0062 p:0012 s:0358 e:000357 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:81
c:0061 p:0011 s:0352 e:000350 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:53
c:0060 p:0021 s:0346 e:000342 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:38
c:0059 p:0047 s:0339 e:000338 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:10
c:0058 p:0008 s:0333 e:000332 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_handling.rb:118
c:0057 p:0003 s:0329 e:000328 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-5.2.6.2/lib/active_record/connection_handling.rb:90
c:0056 p:0008 s:0325 e:000324 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/ar-octopus-0.10.2/lib/octopus/model.rb:159
c:0055 p:0003 s:0321 e:000320 METHOD /home/vital/.rvm/gems/ruby-2.7.7/gems/activerecord-

-- C level backtrace information -------------------------------------------
/home/vital/.rvm/rubies/ruby-2.7.7/lib/libruby.so.2.7(rb_vm_bugreport+0x4ae) [0x7f98fa0cfeae]
/home/vital/.rvm/rubies/ruby-2.7.7/lib/libruby.so.2.7(rb_bug_for_fatal_signal+0xeb) [0x7f98f9f3c16b]
/home/vital/.rvm/rubies/ruby-2.7.7/lib/libruby.so.2.7(sigsegv+0x4d) [0x7f98fa04b07d]
/ruby-2.7.7/lib/libruby.so.2.7(rb_nogvl+0x97) [0x7f98fa0845a7]
[0x7f98f590533c]
[0x7f98f590da2a]
/home/vital/.rvm/rubies/ruby-2.7.7/lib/libruby.so.2.7(vm_call_cfunc+0x126) [0x7f98fa0aef66]
...
7f98fa1f8000-7f98fa1fa000 r--p 00000000 103:02 2230375                   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2

7ffdc5a6c000-7ffdc5a70000 r--p 00000000 00:00 0                          [vvar]
7ffdc5a70000-7ffdc5a72000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0                  [vsyscall]

When I use ruby 2.7.4 it works fine.

rails database setup command can not make the database as I wish?

I am newbie with Ruby Rails and here is my problem.

I created a very simple Rails program by this command

rails new freelancer --database=postgresql --javascript=webpack

And I had no error

In this file

config -> locales -> database.yml

I saw 2 files

database: freelancer_test database: freelancer_development

Then I ran this command

rails db:setup

It showed me this error

Is the server running locally and accepting connections on that socket? Couldn't create 'freelancer_development' database. Please check your configuration. rails aborted! ActiveRecord::ConnectionNotEstablished: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? Caused by: PG::ConnectionBad: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? Tasks: TOP => db:setup => db:create (See full trace by running task with --trace)

I thought that it must created 2 databases freelancer_test and freelancer_development ?

Could you please give me some advices ? Thank you in advance.

jeudi 2 février 2023

error when create a new folder by rails command : "can't find gem railties (>= 0.a) with executable rails (Gem::GemNotFoundException)"?

I am newbie with Rails and here is my problem.

I created a new Rails's folder by this command

rails new freelancer --database=postgresql --javascript=webpack

And it gave me this error :

can't find gem railties (>= 0.a) with executable rails (Gem::GemNotFoundException) from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems.rb:302:in activate_bin_path' from /Users/xxx/.gem/ruby/3.1.2/bin/rails:25:in <main>' from /Users/xxx/.gem/ruby/3.1.2/bin/ruby_executable_hooks:22:in eval' from /Users/xxx/.gem/ruby/3.1.2/bin/ruby_executable_hooks:22:in <main>'

When I checked my ruby version, it gave me this :

ruby 2.6.10p210 (2022-04-12 revision 67958)

When I checked my rails version by the command rails -v, it still show me this error :

can't find gem railties (>= 0.a) with executable rails (Gem::GemNotFoundException)

So I thought that maybe my problem is because of my rails's version it up to date, maybe I must reinstall rails ?

What should I do ? Could you please give me some advices ? Thank you in advance.