lundi 29 novembre 2021

How to use ilike for phone number filter

Hi im fetching the user input and displaying the records that matches the condition, my query will look like

customers = customers.where('customers.contact_num ilike :search', {search: "%#{options[:search_contact]}%"})

here in db the contact number is stored in string with the format (091)-234-5678 like that

on while searching the user on basis of contact number if i search like this

091 it filters the number correctly, but while searching like 0912, it doesn't display record due to the braces, so how to modify the query to neglect the ) and - while searching.. As im new to the domain please help me out

thanks in advance

Custom query to fetch all entries of a table and that only contains first of many duplicates based on a specific column

I have a Location model and the table looks like

   id |      name      | vin |     ip_address    |         created_at         |         updated_at    ----+----------------+------+---------------+----------------------------+------------------------
    0 | default |    0 | 0.0.0.0/0          | 2021-11-08 11:54:26.822623 | 2021-11-08 11:54:26.822623
    1 | admin  |    1 | 10.108.150.143    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    2 | V122  |    122| 10.108.150.122    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885  
    3 | V123 |    123| 10.108.150.123   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    4 | V124  |    124| 10.108.150.124   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    5 | V122  |    122| 10.108.150.122    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    6 | V125  |    122| 10.108.150.125   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885

My method in the Location model

   def self.find_all_non_duplicate
     return self.find(:all, :conditions => "id <> 1")
   end

I want to fetch all entries of the locations table except the entry with id = 1 and that contains only the first entry of many duplicates based on the column ip_address.

Since ip_address of id = 2 and id = 5 is duplicate. I want to keep the first entry of many duplicates i.e., id = 2.

The expected result is

 id |      name      | vin |     ip_address    |         created_at         |         updated_at           ----+----------------+------+---------------+----------------------------+------------------------
 0 | default |    0 | 0.0.0.0/0          | 2021-11-08 11:54:26.822623 | 2021-11-08 11:54:26.822623
 2 | V122  |    122| 10.108.150.122    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
 3 | V123 |    123| 10.108.150.123   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
 4 | V124  |    124| 10.108.150.124   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
 6 | V125  |    122| 10.108.150.125   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885

The entries with id's 1 and 5 to be ignored

dimanche 28 novembre 2021

Unable to remove action_mailbox

I'm using Ruby 3.0.3 + Rails 6.1.4. I tried to remove action_mailbox (and any unused railties) and have the following in my application.rb

%w(
  action_controller/railtie
  action_view/railtie
  active_job/railtie
  sprockets/railtie
).each do |railtie|
  begin
    require railtie
  rescue LoadError
  end
end

I also commented out any action_mailbox related configs.

Here's the Gemfile

# gem 'rails', '~> 6.1', '>= 6.1.4' # note this is commented out. I know it's overkill, but this didn't work
gem 'actionpack', '~> 6.1', '>= 6.1.4'
gem 'actionview', '~> 6.1', '>= 6.1.4'
gem 'activesupport', '~> 6.1', '>= 6.1.4'
gem 'railties', '~> 6.1', '>= 6.1.4'
gem 'sprockets-rails', '~> 3.4', '>= 3.4.1'

However, when I run bundle exec derailed bundle:mem, I still see action_mailbox

  rails/all: 62.25 MiB
    action_mailbox/engine: 33.3594 MiB
      action_mailbox: 33.3281 MiB
        action_mailbox/mail_ext: 33.2969 MiB
          action_mailbox/mail_ext/address_equality.rb: 31.9375 MiB
            mail/elements/address: 31.9375 MiB
              mail/parsers/address_lists_parser: 31.9063 MiB (Also required by: mail/parsers)
                mail/parsers: 1.7656 MiB
                  mail/parsers/received_parser: 1.1875 MiB

I don't think any Gems are depending on it, but is there a way that I can find out?

I tried running bundle exec gem dependency -R but I'm not sure if it's very helpful:

Gem actionmailbox-6.1.4
  actionpack (= 6.1.4)
  activejob (= 6.1.4)
  activerecord (= 6.1.4)
  activestorage (= 6.1.4)
  activesupport (= 6.1.4)
  mail (>= 2.7.1)
  Used by
    rails-6.1.4 (actionmailbox (= 6.1.4))

Gem rails-6.1.4
  actioncable (= 6.1.4)
  actionmailbox (= 6.1.4)
  actionmailer (= 6.1.4)
  actionpack (= 6.1.4)
  actiontext (= 6.1.4)
  actionview (= 6.1.4)
  activejob (= 6.1.4)
  activemodel (= 6.1.4)
  activerecord (= 6.1.4)
  activestorage (= 6.1.4)
  activesupport (= 6.1.4)
  bundler (>= 1.15.0)
  railties (= 6.1.4)
  sprockets-rails (>= 2.0.0)

samedi 27 novembre 2021

Having trouble running rails commands

Errors

/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/commands/rake/rake_command.rb:19:in `block in perform'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/command.rb:50:in `invoke'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/commands.rb:18:in `<main>'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/loaded_features_index.rb:100:in `register'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/full-stack-review/cheese-shop/bin/rails:5:in `<top (required)>'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client/rails.rb:30:in `load'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client/rails.rb:30:in `call'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client/command.rb:7:in `call'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client.rb:30:in `run'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/bin/spring:49:in `<top (required)>'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/binstub.rb:11:in `load'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/binstub.rb:11:in `<top (required)>'
/full-stack-review/cheese-shop/bin/spring:10:in `block in <top (required)>'
/full-stack-review/cheese-shop/bin/spring:7:in `tap'
/full-stack-review/cheese-shop/bin/spring:7:in `<top (required)>'

Steps I tried

  • Updating ruby gems
  • Spring stop
  • Uninstall Ruby on Mac w/ rvm

I am not sure at which point this error started to persist. Tried my best to restore this codebase.

vendredi 26 novembre 2021

To upgrade Rails 5.1 migrations to Rails 6.0, I can't exchange add_attachment to what

I am upgrading ruby version from 2.5.7 to 3.0.0 So I upgrade rails version from 5.1 to 6.1 also.

After version upgrade, I tried to migrate database. Then I am facing following issues: [screenshot][1]

Here is the migrations file source:

class AddAttachmentAvatarToUsers < ActiveRecord::Migration[5.1]
  def self.up
    change_table :users do |t|
    t.attachment :avatar
  end
end

  def self.down
    remove_attachment :users, :avatar
  end
end

I am using gem 'paperclip', '~> 5.0.0'

after googling I tried with this codes.

class AddAttachmentAvatarToUsers < ActiveRecord::Migration[6.1]
  def self.up
    add_attachment :users, :avatar
  end

  def self.down
    remove_attachment :users, :avatar
  end
end

Then it causing bellow issues

[screenshot2][2]

Pls help me fix this issue. [1]: https://i.stack.imgur.com/SFNmK.png [2]: https://i.stack.imgur.com/fMHYY.png

How to include a if condition inside where clause in rails

I have the following method:

def add_books(year, industry, author_id=nil)
  Books.where(publication_year:year, author: author_id)
end

How can I update the query to not filter by author_id if it is not passed?

Rspec reloads removes the value that updated earlier

why reload removes the values that has been updated on before(:each)

is there any other approach for doing such things

thanks in advance i have written my rspec as below

let!(:book){FactoryGirl.create(:book)
let!(:book2){FactoryGirl.create(:book)

before(:each) do
  book.update_column(name:"my new book")
  book2.update_column(name:"my second book")
end

it "does updation of name" do
  data = book.rename_book
  expect(book.reload.name).to eq("some new name")
  expect(book2.reload.name).to not_eq("some new name") // here it removes the book name and make it as nil, how to prevent this
end

//the book2.reload is removes the book name and update it as nil, as how to fix it as it should display the second book name, instead it displays nil for that book.

mardi 23 novembre 2021

While running the rspec it shows does not implement( allow_any_instance_of )

My rspec line

allow_any_instance_of(School).to receive(:admission).and_return(:body)

I have my admission method in my lib/school.rb module School

def self.admission()

like this, but when i run the rspec it throws error like

Failure/Error: allow_any_instance_of(School).to receive(:admission),and_return(:body)
       School does not implement #admission

lundi 22 novembre 2021

Specified 'postgresql' for database adapter, but the gem is not loaded. Add `gem 'pg'` to your Gemfile

Error setting up my database when trying to clone this repo (https://github.com/ssaffa38/prelaunchr) and running it on my local server. Where I'm getting is stuck is where it is asking to setup local database.

The code I'm putting in is:

bundle exec rake db:create
bundle exec rake db:migrate

The error I keep getting is:

Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).

What I've tried to do is update my Gemfile, but still have no luck.

Here is the full error report in my terminal (not sure if this is where I have to post this...):

Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:174:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:6:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:76:in establish_master_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:14:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:93:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:107:in block in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:278:in block in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:106:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in block in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:219:in block in invoke_with_call_chain' /Users/sahrsaffa/.rvm/rubies/ruby-2.5.3/lib/ruby/2.5.0/monitor.rb:226:in mon_synchronize' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:199:in invoke_with_call_chain' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:188:in invoke' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:160:in invoke_task' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block (2 levels) in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:125:in run_with_threads' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:110:in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:83:in block in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:186:in standard_exception_handling' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:80:in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in load' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in ' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in ' Couldn't create database for {"adapter"=>"postgresql", "database"=>"prelaunchr_development", "host"=>"localhost"} Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:174:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:6:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:76:in establish_master_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:14:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:93:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:107:in block in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:278:in block in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:106:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in block in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:219:in block in invoke_with_call_chain' /Users/sahrsaffa/.rvm/rubies/ruby-2.5.3/lib/ruby/2.5.0/monitor.rb:226:in mon_synchronize' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:199:in invoke_with_call_chain' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:188:in invoke' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:160:in invoke_task' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block (2 levels) in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:125:in run_with_threads' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:110:in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:83:in block in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:186:in standard_exception_handling' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:80:in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in load' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in ' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in ' Couldn't create database for {"adapter"=>"postgresql", "database"=>"prelaunchr_test", "host"=>"localhost"} rake aborted! Gem::LoadError: Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:174:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:109:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in '

Caused by: Gem::LoadError: can't activate pg (~> 0.15), already activated pg-1.2.3. Make sure all dependencies are added to Gemfile. /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/postgresql_adapter.rb:16:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:274:in require' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:274:in block in require' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:240:in load_dependency' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:274:in require' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:175:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:109:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in ' Tasks: TOP => db:create (See full trace by running task with --trace)

any help would be greatly appreciated.

Ruby on Rails allow multiple clicks for link_to

I'm new to Ruby on Rails and have found myself stumped.

I am trying to create a link_to item in my view that will not be disabled after being clicked once. It's a page listing people's names and their attendance. The names are colored red if absent and green if present and I'd like the user to be able to toggle the attendance more than once for each person.

Here is the code for my view and controller (note I am using websockets here as well to update the coloring of the button after being clicked):

index.html.erb:

    <div id="reader-attendance-<%= member.id %>">
      <% if member.present == true %>
          <%= link_to member.last_name.upcase, attendance_path(:id => member.id, :present => false), remote: true, class: "btn btn-outline-success btn-14" %>
      <% else %>
        <%= link_to member.last_name.upcase, attendance_path(:id => member.id, :present => true), remote: true, class: "btn btn-outline-danger btn-14" %>
      <% end %>
    </div>

controller.rb:

  def attendance
    member = Member.find(params[:id])
    if(params[:present] == 'true')
      member.present = true
    else
      member.present = false
    end
    member.save
    vote_member = VoteMember.where(member_name: member.display_name)[0]
    if vote_member.vote_type == 'Absent'
      vote_member.vote_type = ''
      vote_member.save
    end
    ActionCable.server.broadcast(
      'attendance_channel',
      {
        member_id: member.id,
        present: params[:present],
        vote_member_id: vote_member.id,
        total_abs: Member.where(present: false).count(),
        member_name: member.last_name.upcase
      }
    )
  end

Solutions I have tried:

  1. I've read that you can add an option to config so that the disable option is turned off as follows: Rails.application.configure do config.action_view.automatically_disable_submit_tag = false end The it seems like this is not supported, however, for the link_to tag and is only supported for button_to

  2. I added the content in #1 to config and then I've tried the button_to option as follows with no success. I have a feeling it's the way that I've passed the parameters in here:

  <%=button_to member.last_name.upcase ,:action => :attendance, :id => member.id, :present => false, remote: true, class: "btn btn-outline-success btn-14" %>

I am working with the following versions:

Rails 6.1.4.1 Ruby 3.0.1

Thanks in advance! Please let me know if other info would be helpful.

samedi 20 novembre 2021

How do I keep the dash in the humanize string

Keep dash for humanize hash key

  1. Replaces underscores with spaces if any.
  2. Capitalizes the first word.
  3. The left character and right character of the dash(-) is in Uppercase if any.

For example:

this_is_a_test -> This is a test

foo_bar -> Foo bar

rock-on-a-roll -> Rock-On-A-Roll

a_full-stack_dev -> A_Full-Stack_dev

vendredi 19 novembre 2021

Ruby get variable in another method (undefined local variable or method )

The function is to display the correct final price for each number. For example, if there are 5 bottles, it should get results for: 5 * 2 + 10 = 15

The enum example is:

class AaaBbb < ApplicationRecord

 enum number: { apple: 1, bottle: 2, headphone: 3, wallet: 5 }

The function to get value is like this :

def find_value(key)
  val = AaaBbb.numbers[key] # this will be nil if the key isn't found
  val || 0
end

The function to calculate the money is (HAS ERROR HERE, NEED TO UPDATE):

  def calculate
      quantity * find_value + 10
  end

Now it has an error:

undefined local variable or method `val' for #AaaBbb:0x00007f7cd9443240 Did you mean? eval Extracted source (around line #33):

   def calculate
     quantity * val + 10
   end

Question:

How to solve the problem by modifying the find_value or calculate functions? If you have any better ideas, please feel free to share.

Ruby on rails: function to find value by key

I just encountered a problem with ruby syntax:

The enum example is:

class AaaBbb < ApplicationRecord

 enum number: { a: 1, b: 2, c: 3, d: 5 }

or

class AaaBbb < ApplicationRecord

 enum number: { "a" => 1, "b" => 2, "c" => 3, "d" => 5 }

The function is:

  def find_value
    AaaBbb.numbers.each do |key, value|
        puts "#{key} = #{value}"
      if key == AaaBbb.numbers[:key] (WRONG CODE HERE, NEED TO FIX)
        return value
      else
        return 0
      end
    end
  end

So I am trying to write a function that if it finds the key, then return the value. For example that if I find look up some product(key), it will return the correct price(value) to display.

Thanks, and feel free to share if you have any better way to solve it.

fedena : rake aborted school not selected

I was installing fedena on ubuntu installed on wsl and the database creation and migration was successful but when run the command rake fedena:plugins:install_all to install the plugins. in the middle this error pops up that school Not Selected and here is the error trace.

School Not Selected
/root/fedena/vendor/plugins/acts_as_multi_school/lib/multischool/read.rb:46:in `with_school'
/root/fedena/vendor/plugins/acts_as_multi_school/lib/multischool/read.rb:22:in `find_with_school'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1954:in `find'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1954:in `find_or_create_by_config_key'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1940:in `send'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1940:in `method_missing_without_paginate'
/root/fedena/vendor/plugins/will_paginate/lib/will_paginate/finder.rb:170:in `method_missing'
/root/fedena/app/models/configuration.rb:90:in `find_or_create_by_config_key'
/root/fedena/db/seeds.rb:26
/root/fedena/db/seeds.rb:2:in `each'
/root/fedena/db/seeds.rb:2
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load_without_new_constant_marking'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rails-2.3.5/lib/tasks/databases.rake:215
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/root/fedena/lib/tasks/fedena_plugin_install.rake:31
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.8.7-p374/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/bin/rake:31
/usr/local/rvm/gems/ruby-1.8.7-p374/bin/rake:19:in `load'
/usr/local/rvm/gems/ruby-1.8.7-p374/bin/rake:19

the code causing this error appears to be this code:

module MultiSchool

  module Read

    def self.extended (base)
      
      eigen_class = class << base;self;end
      
      ["find","count","sum","exists?"].each do |method|
        
        matches = method.match /([\w\d_]+)(\?|!|=)?$/
        
        eigen_class.send :define_method, "#{matches[1]}_with_school#{matches[2]}" do |*args|

          options = args.extract_options!
          skip_multischool = options.delete :skip_multischool
          args << options unless options.empty?
          
          result = if skip_multischool || Thread.current[:skip_multischool].present?
            send("#{matches[1]}_without_school#{matches[2]}",*args)
          else
            with_school do
              send("#{matches[1]}_without_school#{matches[2]}",*args)
            end
          end
          result
        end

        eigen_class.send :alias_method_chain, method, :school
      end

    end

    def skip_multischool
      Thread.current[:skip_multischool]=true
      yield
    ensure
      Thread.current[:skip_multischool]=nil
    end

    private

    def with_school      
      target_school = MultiSchool.current_school
      if target_school.nil?
        raise MultiSchool::Exceptions::SchoolNotSelected,"School Not Selected"
      else
        with_scope(:find => {:conditions  => {:school_id  => target_school.id}}) do
          yield
        end
      end
    end

  end

end

looks the MultiSchool.current_school is returning nil which sets the variable target_school to nil so the above exception occurs of school not selected but I don't know where to from here?

Could you please help me out this issue.

How can I retrieve Basic Authentication credentials from the header in ruby?

Can anyone explain to me how to get a username and password from a request header in ruby?

jeudi 18 novembre 2021

Rails Ransack gem: search for multiple values with one condition

I use ransack gem and I have a select field event_id,if choose option Event Online will search with multiple values. This is my query:

ransack("job_name_cont" => job_name, "event_id_eq" => event_id).result

event_ids is string or array - eg: 90 or [ 145, 147, 148 ]. When search with option Event Online, the result returning errors:

[1] pry(Job)> ransack("job_name_cont" => job_name, "event_id_eq" => event_ids).result 
NoMethodError: undefined method `to_i' for [145, 147, 148]:Array
Did you mean?  to_s
               to_a
               to_h

My model:

class Job < ActiveRecord::Base
  belongs_to :event
end

class Event < ActiveRecord::Base
  has_many :jobs, dependent: :destroy
end

How can i search with event_id is array?

mercredi 17 novembre 2021

attr_encrypted gem sometimes saving null value in database

I am running rails 3 version and using attr_encrypted gem version '1.2.1' . sometimes i have seen that nil entry is getting stored into column encrypted_private_key.

Below is my model

class Device < ActiveRecord::Base
  attr_encrypted :private_key, :key => proc {|device| device.log }
end

Below is how i am trying to store value in column encrypted_private_key

device = Device.new
device.private_key = "XYZ" 
device.save

after doing device.save if i do device.encrypted_private_key then sometimes i am getting nil value. what could be the reason for this? This issue is not coming everytime but sometime.

getting user info using JWT Token in ruby

I want to extract user info like User ID and User Name using JWT token. I was able to do it in django like this-

    valid_data = TokenBackend(algorithm='HS256').decode(token, verify=False)
    user_id = valid_data['user_id']
    return user_id

but how do I do it using ruby. Thanks :)

mardi 16 novembre 2021

Ruby On Rails executing with wrong version

I try to Run my new rails app using RubyMine, and it seems to use some wrong Ruby version and i can't figure out why! I used rbenv to setup the environment .ruby-version shows 3.0.2

/bin/zsh -c "bash -c 'env RBENV_VERSION=2.7.2 /usr/local/Cellar/rbenv/1.2.0/libexec/rbenv exec ruby /Users/ran/source/rails/MySite/bin/rails server -b 0.0.0.0 -p 3000 -e development'" Your Ruby version is 2.7.2, but your Gemfile specified 3.0.2

ran@ran-mac MySite % ruby --version ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-darwin20] ran@ran-mac MySite %

What's wrong? I can not understand where it takes this 2.7.2 from! Thanks

lundi 15 novembre 2021

Error installing ruby 2.7.0 with rvm and openssl

I want to install ruby 2.7.0 and compile it with openssl. So, I did the following:

rvm package install openssl
rvm install 2.7.0 --with-openssl-dir=/home/arnab/.rvm/usr

Here, $HOME=/home/arnab But, it gives the error and the make.log shows:

/usr/bin/ld: /home/arnab/.rvm/usr/lib/libssl.a(s23_meth.o): Relocation R_X86_64_32 against 'ro.data' can not be used when making a shared object; recompile with -fPIC
/home/arnab/.rvm/usr/lib/libssl.a :error adding symbol: Bad value

Well, it tells me recompile with fPIC but how do I do that? Any help is appreciated.

dimanche 14 novembre 2021

Rails 3 uninitialized constant when using thread

i am running rails 3 thread to improve the performance of the rake task. sometimes i am getting uninitialized constant when i am trying to access outside class from my current class. as an example when i am trying to access NotificationService class from NotificationApp as shown below then getting error as uninitialized constant NotificationService. This error is not coming every time. sometimes rake task is running fine without the error and sometimes same rake is failing with uninitialized constant. what could be the reason for this and how can i fix this issue?

class NotificationApp < ActiveRecord::Base
  def signal_event
    NotificationService.notify
  end
end

vendredi 12 novembre 2021

How to maintain a copy of a hash with original values after changing some of its values in ruby?

I have tried to phrase this to the best of my ability. I have a hash that I perform some operations on but before I do this, I store this hash in another variable. Now when I access this variable, the values seem to have changed, how can I go around it. Example:

hash = {a: "1", b: "2", c: "3"}
hash_copy = hash
hash["a"]=4
puts(hash_copy["a"]) #prints 4 instead of 1

How can I get the put statement to print 1 instead of 4, that is, print the original value.

Updating to Ruby 3.0.x with Rails: symbol not found in flat namespace '_RHASH_EMPTY_P'

Having issues upgrading my rails project on my M1 Mac related to Debase not compiling due to symbol not found in flat namespace '_RHASH_EMPTY_P'

OS: Monterey 12.0.1 Machine: Mac mini (m1, 2020) Ruby version: 3.0.2 Rails: 6.1.4.1

I've tried removing Gemfile.lock and totally reinstalling brew/rbenv/rails. The app runs successfully on the Ruby:3.0.2 docker image.

When I run rails s, I get the following stack trace:

/Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require': dlopen(/Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/debase-0.2.4.1/lib/debase_internals.bundle, 0x0009): symbol not found in flat namespace '_RHASH_EMPTY_P' - /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/debase-0.2.4.1/lib/debase_internals.bundle (LoadError)
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/debase-0.2.4.1/lib/debase.rb:4:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/ruby-debug-ide-0.7.3/lib/ruby-debug-ide.rb:9:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:60:in `block (2 levels) in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:55:in `each'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:55:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:44:in `each'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:44:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler.rb:175:in `require'
    from /Users/josh/Documents/Development/hub/config/application.rb:20:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:138:in `block in perform'
    from <internal:kernel>:90:in `tap'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:135:in `perform'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/thor-1.1.0/lib/thor/command.rb:27:in `run'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/command/base.rb:69:in `perform'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/command.rb:48:in `invoke'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/commands.rb:18:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/Documents/Development/hub/bin/rails:9:in `<top (required)>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `load'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `call'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client/command.rb:7:in `call'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client.rb:30:in `run'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/bin/spring:49:in `<top (required)>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `load'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `<top (required)>'
    from <internal:/Users/josh/.rbenv/versions/3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
    from <internal:/Users/josh/.rbenv/versions/3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
    from /Users/josh/Documents/Development/hub/bin/spring:15:in `<top (required)>'
    from bin/rails:3:in `load'
    from bin/rails:3:in `<main>'

uninitialized constant Rails::Plugin::Authorization when run `rake db:migrate`

I was populating a rails application fedena database with the command rake db:migrate, I am getting an error:

rake aborted! uninitialized constant Rails::Plugin::Authorization

when I tried to run the rake command with --trace I got the following:

** Execute environment
rake aborted!
uninitialized constant Rails::Plugin::Authorization
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing'
/mnt/c/users/usrx/Documents/myapp/app/vendor/plugins/acts_as_multi_school/init.rb:15:in `evaluate_init_rb'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin.rb:158:in `evaluate_init_rb'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin.rb:154:in `evaluate_init_rb'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin.rb:48:in `load'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin/loader.rb:38:in `load_plugins'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin/loader.rb:37:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin/loader.rb:37:in `load_plugins'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:369:in `load_plugins'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:165:in `process'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:113:in `send'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:113:in `run'
/mnt/c/users/userx/Documents/myapp/app/config/environment.rb:5
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `gem_original_require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/tasks/misc.rake:4
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.8.7-head/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:607:in `invoke_prerequisites'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:604:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:604:in `invoke_prerequisites'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:596:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.8.7-head/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/bin/rake:31
/usr/local/rvm/gems/ruby-1.8.7-head/bin/rake:19:in `load'
/usr/local/rvm/gems/ruby-1.8.7-head/bin/rake:19
/usr/local/rvm/gems/ruby-1.8.7-head/bin/ruby_executable_hooks:22

I think the line causing the error is in the file init.rb which is:

Authorization::AUTH_DSL_FILES << "#{RAILS_ROOT}/vendor/plugins/acts_as_multi_school/config/acts_as_multi_school_auth.rb"

and I do not know how can this be solved!

jeudi 11 novembre 2021

Customize Fedena flash messages

How can I customize flash messages from Fedena? for example in the forgot page, when user supplies not existing username, it displays this message no username exists with username How can I customize that message to the user supplied does not exist! in the source code I see for example, this code flash[:notice] = "#{t('flash18')}". when traced the t() function. it redirects to the translator.rb which contains

module ActionController #:nodoc:
  class Base
    
    # Add a +translate+ (or +t+) method to ActionController that is context-aware of what controller and action
    # is being invoked. Initial scoping will be [:controller_name :action_name] when looking up keys. Example would be
    # +['posts' 'show']+ for the +PostsController+ and +show+ action.
    def translate_with_context(key, options={})
      Translator.translate_with_scope([self.controller_name, self.action_name], key, options)
    end
  
    alias_method_chain :translate, :context
    alias :t :translate
  end
end

module ActiveRecord #:nodoc:
  class Base

    def translate(key, options={})
      Translator.translate_with_scope([self.class.name.underscore], key, options)
    end
  
    alias :t :translate
  
    # Add translate as a class method as well so that it can be used in validate statements, etc.
    class << Base
    
      def translate(key, options={}) #:nodoc:
        Translator.translate_with_scope([self.name.underscore], key, options)
      end
    
      alias :t :translate
    end
  end
end

but I don't see the string I was after i.e no user exists with username. How can I customize these messages in fedena?

mercredi 10 novembre 2021

Attachments adding duplicates in active storage

I have a Message model which has

 has_many_attached :attachments

My functions:

  def update_attachment
        remaining_attachment_ids = attachment_params[:existing]
        if message.attachments.attached? && errors.empty?
          message.attachments.where.not(id: remaining_attachment_ids).purge
          message.reload
          puts "AFTER DELETE"
          puts message.attachments.count
        end
        message.reload

        attach_new_files
      end

      def attach_new_files
        if attachment_params[:new]
          puts attachment_params[:new].map { |attachment| attachment["blob_signed_id"]}
          message.attachments.attach(attachment_params[:new].map { |attachment| attachment["blob_signed_id"] })
          message.reload
          puts "AFTER UPDATE"
          puts message.attachments.count
        end
      end

I'm trying to purge some and then add new attachments in a two step process. First I purge the attachments and the message.attachments.count is getting printed correctly.

However when I do attach_new_files, After the attachments I'm getting an extra count. For example, I have only 2 items in attachment_params[:new] array. When I print the count after attaching, It's showing 3. I have supplied only 2 blob_signed_ids to attach. What might be the issue here?

mardi 9 novembre 2021

Problem with remote Button method post to redirect in controller

My problem: When place is not present controller does not redirect to the route i want.

I have a link_to , check_payer post route

<%= link_to "Click here", check_payer_path, method: :post, remote: true %>

this methods verify if place is present and if true is not redirecting to billings_path

  def check_payer
    if @place.present?
      redirect_to billings_path
    end
  end

If place is not present it will render check_payer.js.erb that opens a form modal.

$('#modal-check-payer').find(".modal-content").html("<%= j render partial:'place_billing_infos/check_payer_modal' %>");
$("#modal-check-payer").modal();

And this nested form call update_payer_path patch.

<%= simple_nested_form_for @place_billing_info, url: update_payer_path, html: { 
autocomplete: 'off', class: "form-horizontal" } do |place_form| %>

<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span 
aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel"><%= html_icon_member %> <span class="text- 
normal">Insira seu CPF/CNPJ para visualizar a fatura.</span></h4>
</div>

 <div class="modal-body">
 <div class="row">
  <div class="col-sm-12 text-muted">
    <%= place_form.simple_fields_for :billing_info do |info| %>
      <div class="col-md-4  col-xs-8 modal-text-left"><%= info.input :payer_cpfcnpj, 
 wrapper: :default_form, label: 'Cpf/Cnpj', required: true %></div>
     <% end %>
   </div>
 </div>
</div>

<div class="modal-footer">
<button type="submit" class="btn btn-info new-member-submit">Exibir fatura</button>
</div>
<% end %>

Getting error trying to start ruby on rails

I created a new app with ruby on rails and tried to start it, then got this error.

1 - have ruby-dev-kit

2 - ruby version 2.7.0

Tried to fix this error in many ways. I use Linux

Traceback

       11: from /usr/lib/ruby/2.7.0/psych/nodes.rb:2:in `<main>'
        10: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
         9: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
         8: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
         7: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
         6: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
         5: from /usr/lib/ruby/2.7.0/psych/nodes/node.rb:2:in `<main>'
         4: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
         3: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
         2: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
         1: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require': superclass mismatch for class StringIO (TypeError)

ActiveStorage::FileNotFoundError in direct upload Attach using Amazon s3 presigned url

I'm using presigned_post for generating signed_url to upload file to s3 directly from client. The file is getting uploaded correctly and returning response with a generated blob_signed_id.

However , when I try to attach the file to the object , it is showing FileNotFoundError.

  def generate_url
    load_aws_credentials
    load_bucket
    blob = create_blob
    presigned_url = @s3_bucket.presigned_post(
      key: "#{Rails.env}/#{SecureRandom.uuid}/${filename}",
      success_action_status: "201",
      signature_expiration: (Time.now.utc + 15.minutes),
    )
    response = { url: presigned_url.url, url_fields: presigned_url.fields }
    response[:blob_signed_id] = blob.signed_id
    response
  end

  private
    attr_reader :blob_args

    def create_blob
      blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_args)
      blob
    end 

The blob is getting created and a signed_id is returned.

 def take_actions
        @message = ::Widget::Message.new(message_params)
        attach_files
        if @message.save
         ...
        else
         ...
        end
      end

  def attach_files
      if data["attachments"]
        data["attachments"].map do |attachment|
          @message.attachments.attach(attachment["blob_signed_id"])
        end
      end
    end

When I try to attach the file using the signed_id it is showing file not found.

Presigned url upload and linking using active storage

I'm trying to upload attachments via AWS s3 presigned url. It is done as a 2 step process . First I created an API for generating a presigned post url and sent to client React App.

class Admin::PresignedUploadController < ApplicationController
  before_action :authenticate_user!, only: [:index]
  before_action :load_aws_credentials, only: [:index]
  before_action :load_bucket, only: [:index]

  def index
    presigned_url = @s3_bucket.presigned_post(
      key: "#{Rails.env}/#{SecureRandom.uuid}/${filename}",
      success_action_status: "201",
      signature_expiration: (Time.zone.now.utc + 15.minutes)
    )

    data = { url: presigned_url.url, url_fields: presigned_url.fields }

    render json: data, status: :ok
  end

  private

    def load_bucket
      @s3_bucket = Aws::S3::Resource.new(
        region: ENV["AWS_REGION"],
        credentials: @aws_credentials
      ).bucket(ENV["AWS_BUCKET_NAME"])
    end

    def load_aws_credentials
      @aws_credentials = Aws::Credentials.new(
        ENV["AWS_ACCESS_KEY_ID"],
        ENV["AWS_SECRET_ACCESS_KEY"]
        )
    end
end

I'm able to upload the file via a post request to the url and get a response from s3.

<PostResponse>
    <Location>https://neeto-chat-staging-v1.s3.amazonaws.com/development%2Fa185e6a8-b4eb-402e-a11a-a2c8ed48bdea%2Fwallpaper-photos-3.jpg</Location>
    <Bucket>neeto-chat-staging-v1</Bucket>
    <Key>development/a185e6a8-b4eb-402e-a11a-a2c8ed48bdea/wallpaper-photos-3.jpg</Key>
    <ETag>"2cbc861b2a9e0c48c7a7edf565f6a509"</ETag>
</PostResponse>

My first problem is that the Location is not accessible and it is showing access denied. I hope it might get solved after giving GET permission in AWS s3.

Is the Location returning the public url of the file?

Do I have to make an additional request to attach it to the model using active record or can it be done automatically using active record?

My schema for attachments:

  create_table "active_storage_attachments", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.uuid "record_id", null: false
    t.uuid "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness",
unique: true
  end

My model Message has:

 has_many_attached :attachments

 def get_url(attachment)
      Rails.application.routes.url_helpers.rails_blob_path(
        attachment, only_path: true
      )
    end

def get_attachments
  if attachments.attached?
    self.attachments.attachments.map do |attachment|
      {
        filename: attachment.filename,
        url: get_url(attachment),
        id: attachment.id
      }
    end
  end
end

dimanche 7 novembre 2021

Rails 5: Is Nested forms set up correct

If I want a Nested Form for volunteer_shift inside my assignment/_form

How should my model associations be set up?

My current associations look like this..but I am not sure they are correct if the volunteer_shift partial sits inside the assignment form....

When I try to open the "add new record" form...my assignment#new action errors out...

error message

Completed 500 Internal Server Error in 30ms (ActiveRecord: 2.7ms)



NoMethodError - undefined method `build' for nil:NilClass:
  app/controllers/assignments_controller.rb:21:in `new'

Here is my new action...

  # GET /assignments/new
  def new
    @assignment = Assignment.new
    # binding.pry
    @assignment.volunteer_event.build   <----Line 21
    @my_url = {:action => "create", :id => params[:id]}
  end

Here are my current models associations...

class Assignment < ApplicationRecord
  attr_accessor :volunteer_event
  belongs_to :volunteer_shift
  has_one :volunteer_task_type, :through => :volunteer_shift, :source => :volunteer_task_type
  belongs_to :contact ,optional: true
  validates_presence_of :volunteer_shift #belongs_to takes care of this now
  validates_associated :volunteer_shift
  accepts_nested_attributes_for :volunteer_shift, allow_destroy: true
...
class VolunteerShift < ApplicationRecord
  has_many :assignments
  belongs_to :volunteer_event
...

class VolunteerEvent < ApplicationRecord
  belongs_to :volunteer_default_event
  has_many :volunteer_shifts, :dependent => :destroy
  has_many :resources_volunteer_events, :dependent => :destroy
  validates_associated :volunteer_shifts

And inside my assignment/form

<%= form_for @assignment, :url => @my_url, remote: true do |f| %>
...
          <!--VOLUNTEER SHIFT-->
          <!--TODO: make this a partial under field_for-->
          <%= f.fields_for :volunteer_shift do |builder| %>
            <%= render 'volunteer_shift_fields', vs: builder %>
          <% end %>
...
<% end %>

and if you want to see the volunteer_shift_fields partial


<div class="name large flex-row">
  <%= vs.label :volunteer_shift %>
</div>
<div id="volunteer_shift" class="d-flex flex-row">
  <div class="col-sm-12 p-2">
    <div id="volunteer_shift" class="text-right">
      <!-- old if: if class is assignment show volunteer shift else show default shift -->
      <!--  we need default shift here...NO assignment is attached-->
      <div class="field">
        <%= vs.label :volunteer_task_type_id %>
        <%= select_tag 'volunteer_task_type_id', options_from_collection_for_select([VolunteerTaskType.new(:description => ""),  VolunteerTaskType.instantiables.effective_on(Date.today)].flatten, "id", "description")  %>
      </div>
      <div class="field">
        <%= vs.label :roster_id %>
        <%= select_tag 'roster_id', options_from_collection_for_select([Roster.new(:name => ""), Roster.all].flatten, "id", "name") %>
      </div>
      <div class="field">
        <%= vs.label :program_id %>
        <%= select_tag 'program_id', options_from_collection_for_select([Program.new(:name => ""), Program.where(:volunteer => true)].flatten, "id", "name")%>
      </div>
      <div class="field">
        <%= vs.label :set_description %>
        <%= vs.text_field(:set_description, nil) %>
      </div>
      <div class="field">
        <%= vs.label :set_date, "Date" %> <
        <%= vs.text_field(:set_date, nil) %>
      </div>
    </div>
  </div>
</div>

Are my model associations correct? What is my "assignment#new" action missing?

samedi 6 novembre 2021

How to read realtime ActiveRecord in Ruby on Rails

I want to read DATA which I have recently save in rails console to show up on my index page by real time.

  • Rails 6.1.4
  • Ruby 2.7.0

How should I do? or Does anyone have got a solution for making this?

vendredi 5 novembre 2021

Is there a way to access files that Rails has minified and compressed externally?

I know that the Rails asset pipeline will, under normal circumstances, minify and compress all JS files into one, making them smaller/obfuscated but impossible to access directly from another site. I also know that the /public folder contains files that bypass this process, and can be accessed directly by URL.

My question is, is there a way in Rails to combines these processes? Can I minify/compress a file using my Ruby on Rails gems and have it still be accessible by a static URL? I'm aware that I can place JS files in app/assets to have them go through the pipeline, but if I do that will they be accessible externally?

mardi 2 novembre 2021

How can I easily review a server installed dependencies for unpatched plugins?

I am working on a server migration and upgrade, and I don't code in Ruby at all.

Is there an easy way for me to scan / review the gemfile / installed dependencies to check that latest updated / unpatched dependencies?

The code references to a hundred at least dependencies and I am not sure which are no longer the latest stable version.

Rails5 method is not getting called from create action

So I have an old app I'm updating to Rails 5.0.7 (reasons)

I've ported over the original code bases "create" method but this line is giving me grief...

def create
...
    vs.attributes=(params["assignment"]["volunteer_shift_attributes"]) <--- WHY HE NOT CALLED ???
...
end

Note that ["assignment"]["volunteer_shift_attributes"]?

Well in the old code base the assignment model has this method (which I also ported over to the Rails 5 app)...

  def volunteer_shift_attributes=(attrs)
    self.volunteer_shift.attributes=(attrs) 
  end

So I'm guessing this is where is "supposed" to be getting called in the old app... ...but in the new Rails 5 app's assignment model it is not getting called. And I do not know why.

Here is the entire create action...


  def create # FIXME: evil brought over from original code base
    ve = nil
    if !params["id"].blank?
      ve = VolunteerEvent.find(params["id"])
    else
      if params["roster_id"].blank? || params["assignment"]["set_date"].blank?
        ve = VolunteerEvent.new # won't save
      else
        ve = Roster.find_by_id(params["roster_id"]).vol_event_for_date(params["assignment"]["set_date"])
      end
    end
    vs = ve.volunteer_shifts.new
    #    vs.slot_count = 1
    #    vs.volunteer_event_id = ve.id
    #    vs.volunteer_event = ve
    vs.stuck_to_assignment = vs.not_numbered = true
    vs.attributes=(params["assignment"]["volunteer_shift_attributes"]) <--- WHY HE NOT CALLED ???
    a = vs.assignments.new
    a.volunteer_shift = vs
    #    a.volunteer_shift_id = vs.id
    a.attributes = (params["assignment"])
    @assignments = vs.assignments = [a]
    vs.set_values_if_stuck
    vs.assignments = []
    @success = a.valid? && vs.save
    rt = params[:assignment].delete(:redirect_to)
    @my_url = {:action => "create_shift", :id => params[:id]}
    @assignment = a
    if @success
      vs = vs.reload
      @assignment = a = vs.assignments.new
      a.volunteer_shift = vs
      #    a.volunteer_shift_id = vs.id
      a.attributes = (params["assignment"])
      @assignments = vs.assignments = [a]

      if !@success
        vs.destroy
      end
    end
    if @success # and @assignment.volunteer_shift.save
      redirect_skedj(rt, ve.date_anchor)
    else
      # render :partial => 'assignments/new'
      render :partial => 'assignments/edit' #<--original
    end
  end


Here is the entire assignment model, the offending method is around line 117 (a lot of original code I've refactored for Rails 5...apologies for it's length, it is inherited code..adding here in case it is helpful)...

class Assignment < ApplicationRecord
  belongs_to :volunteer_shift
  has_one :volunteer_task_type, :through => :volunteer_shift, :source => :volunteer_task_type
  belongs_to :contact
  validates_presence_of :volunteer_shift
  validates_associated :volunteer_shift
  belongs_to :attendance_type
  belongs_to :call_status_type
  validates_presence_of :set_date, :if => :volshift_stuck
  validates_existence_of :contact, :allow_nil => true

  delegate :set_date, :set_date=, :to => :volunteer_shift
  delegate :set_description, :set_description=, :to => :volunteer_shift

  scope :date_range, lambda { |range|
    joins(volunteer_shift: :volunteer_event)
        .where(volunteer_shifts: { volunteer_events: { date: range } })
  }
  scope :is_after_today, lambda {||
    { :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) > ?', Date.today] }
  }
  scope :on_or_after_today, lambda {||
    { :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) >= ?', Date.today] }
  }
  scope :not_cancelled, -> { where('(attendance_type_id IS NULL OR attendance_type_id NOT IN (SELECT id FROM attendance_types WHERE cancelled = \'t\'))')}
  scope :roster_is_limited_by_program, -> {where("roster_id IN (SELECT id FROM rosters WHERE limit_shift_signup_by_program = 't')").joins(:volunteer_shift)}

  attr_accessor :attendance_type_id



  
  def real_programs
    return [] unless self.volunteer_shift&.roster
    return [] unless self.volunteer_shift.roster.limit_shift_signup_by_program
    self.volunteer_shift.roster.skeds.select{|x| x.category_type == "Program"}.map{|x| x.name}
  end


  def time_range_s
    return "" unless start_time and end_time
    (start_time.strftime("%I:%M") + ' - ' + end_time.strftime("%I:%M")).gsub( ':00', '' ).gsub( ' 0', ' ').gsub( ' - ', '-' ).gsub(/^0/, "")
  end

  def description
    self.volunteer_shift.volunteer_event.date.strftime("%D") + " " + self.time_range_s + " " + self.slot_type_desc
  end

  def roster_title
    self.volunteer_shift.roster.name
  end

  def date
    self.volunteer_shift.date
  end

  def event_date
    date
  end

  def slot_type_desc
    b = (self.volunteer_shift.volunteer_task_type_id.nil? ? self.volunteer_shift.volunteer_event.description : self.volunteer_shift.volunteer_task_type.description)
    b = b + " (#{self.volunteer_shift.description})" if self.volunteer_shift.description and self.volunteer_shift.description.length > 0
    b
  end

  def display_name
    ((!(self.volunteer_shift.description.nil? or self.volunteer_shift.description.blank?)) ? self.volunteer_shift.description + ": " : "") + self.contact_display
  end

  def cancelled?
    (self.attendance_type&.cancelled)
  end

  def attended?
    (self.attendance_type and !self.attendance_type.cancelled)
  end

  def contact_display
    if self.closed
      "(closed)"
    elsif contact_id.nil?
      return "(available)"
    else
      self.contact.display_name + "(#{self.voltask_count})"
    end
  end

  def <=>(other)
    self.date <=> other.date
  end

  def contact_id=(new_val)
    self.write_attribute(:contact_id, new_val)
    self.contact = Contact.find_by_id(new_val.to_i)
  end

  def contact_id_and_by_today
    # Unless the contact id is empty, or the event date is after today.
    !(contact_id.nil? || self.volunteer_shift.volunteer_event.date > Date.today)
  end

  def voltask_count
    self.contact_volunteer_task_type_count ? self.contact_volunteer_task_type_count.attributes["count"] : 0
  end

  before_validation :set_values_if_stuck
  def set_values_if_stuck
    return unless volshift_stuck
    volunteer_shift.set_values_if_stuck(self)
  end

  after_destroy { |record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.destroy; else VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available; end}
  after_save {|record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.save; end}
  after_save { |record| VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available }

  def volunteer_shift_attributes=(attrs) #fixme: why is this not getting called on volunteer_events/create_shift?
    self.volunteer_shift.attributes=(attrs) # just pass it up
  end


  def volshift_stuck
    self.volunteer_shift&.stuck_to_assignment
  end

  def first_time_in_area?
    if self.contact and self.volunteer_shift and self.volunteer_shift.volunteer_task_type
      !ContactVolunteerTaskTypeCount.has_volunteered?(self.contact_id, self.volunteer_shift.volunteer_task_type_id)
    else
      false
    end #  and self.contact_id_changed? moved outside because we use update_attributes
  end


  def all_day_event?
    self.start_time == self.start_time.midnight && self.end_time == self.end_time.midnight ? true : false
  end
end

What am I missing? Why is volunteer_shift_attributes nil when called inside the create action? Why is...

  def volunteer_shift_attributes=(attrs)
    self.volunteer_shift.attributes=(attrs) 
  end

...not getting called?

Thank you for your time.

Rails5 how to refactor a find_or_create_by

I got some old code I'm trying to port over to Rails 5 (reasons)

And I ran into this....

  def vol_event_for_date(date)
    VolunteerEvent.find_or_create_by_description_and_date("Roster ##{self.id}", date)
  end

  def vol_event_for_weekday(wday)
    VolunteerDefaultEvent.find_or_create_by_description_and_weekday_id("Roster ##{self.id}", wday)
  end

I know from a post I've seen on S.O. that the find_by thingie is an old outdated Rails helper of some kind so my question is...how can I refactor this for a Rails 5.0.7 app?

Thank you for your time.