mercredi 6 décembre 2023

Filtering Users with Associated Records by Specific Date in Rails

I'm facing a challenge in a Ruby on Rails application where I need to filter users along with their associated records (Program and Learning), based on a specific date range, but only include those associated records that fall within the given date range.

Models I have the following models:


class User < ApplicationRecord
  has_many :programs
  has_many :learnings
end

class Program < ApplicationRecord
  belongs_to :user
end

class Learning < ApplicationRecord
  belongs_to :user
end

Data Example Consider this data scenario:

User1 has: Program with created_at: Yesterday Learning with created_at: Today User2 has: Program with created_at: Today Learning with created_at: Yesterday

For instance, if I filter for Date.yesterday, I want to get:

User1 with only the Program from yesterday. User2 with only the Learning from yesterday.

Current Approach I've tried various approaches using ActiveRecord queries with joins, where, and eager_load, but I'm either getting users with all their associated records (regardless of the date) or facing issues with structurally incompatible queries.

Can someone suggest a Rails way to achieve this filtering effectively, ensuring that the result is an ActiveRecord::Relation object?

Requirement Given a start and finish date (for example, Date.yesterday), I need to fetch users with their Program and Learning records that were created within this date range. However, the catch is that for a user, I only want to include the Program and Learning records that fall within the specified date range.

I've tried several methods, but none have given me the desired outcome:

  1. Using joins and where: I attempted to use joins with where conditions to filter records. However, this approach either returns users with all their associated records (ignoring the date criteria) or leads to structurally incompatible queries due to the use of or.
Copy code
User.joins(:program, :learnings)
    .where(program: { created_at: start_date..finish_date })
    .or(User.joins(:program, :learnings)
        .where(learnings: { created_at: start_date..finish_date }))

OR

User.joins("LEFT JOIN programs ON programs.user_id = users.id AND programs.created_at BETWEEN '#{start_date}' AND '#{finish_date}'").joins("LEFT JOIN learnings ON learnings.user_id = users.id AND learnings.created_at BETWEEN '#{start_date}' AND '#{finish_date}'")
  1. Subqueries with where: I also experimented with subqueries inside where, but it didn't filter the associated records based on the date criteria.
User.where(id: Program.select(:user_id).where(created_at: start_date..finish_date))
    .or(User.where(id: Learning.select(:user_id).where(created_at: start_date..finish_date)))

mardi 5 décembre 2023

How to handle the params for accepts_nested_attributes_for for has_many association containing a lot of fields on both associated table

I have user model which has has_many association with building model. Initially I was creating the user and the building seperately by using user.create and user.buildings.create because there were some field in the table such that if that field is true then only it create the building and in building also there were condition that if a conditional field in building will be true then more field data will be added to the building. Everything was running smooth till a user create a single building. But when a user started to create more building it bursts the code. Below is the code of users_controller

def create
      role = Role.find_by(id: params[:user][:role_id])
      if role.nil?
        render json: { error: 'invalid role' }, status: :unprocessable_entity
      else
        user = User.new(user_params)
        user.role_id = role.id
        ActiveRecord::Base.transaction do
          if user.save
            # If the user is a technician, handle equipment_params
            if role.name.downcase == 'technician'
              equipment_ids = params[:user][:equipment_id]
              handle_technician_params(user, equipment_ids)
            end
            # If the user is a customer, handle customer_params
            if role.name.downcase == 'customer'
              handle_customer_params(user)
            end
            # Generate a new authentication token for the user
            token, refresh_token = generate_tokens(user.id)
            render json: {  message: 'User created successfully', authentication_token: token, user: user, meta: {photos: UserSerializer.new(user) }}, status: :ok
          else
            render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
          end
        end
      end
    end
def handle_customer_params(user)
      if user_params[:is_customer_direct_point_of_contact] == 'true'
        handle_building_params(user)
      else
        handle_service_params(user)
      end
    end

    def handle_building_params(user)
      building_params = params.require(:building).permit(:service_address_line1, :service_address_line2, :service_zip_code, service_images: [])
      building = user.buildings.create(building_params)
    end
    def handle_service_params(user)
      service_params = params.require(:building).permit(:service_address_line1, :service_address_line2, :service_zip_code, :name, :phone_number, :email, :tax_id, service_images: [])
      building = user.buildings.create(service_params)
    end

I tried to change it to use accepts_nested_attributes_for for direct creating the user and building but did'nt understand how to do that. Is there any also other way to do that?

lundi 4 décembre 2023

Issue when Rounding Decimal values

I am building a test billing application, built in rub on rails, Jquery and Postgres DB (using decimal columns)

This is the below way I am storing values, but I think that is not the way it should save the values

Product 1: 57.5

Charge: 1.7249999999999999

S-Tax: 0.13799999999999998

C-Tax: 4.6

Total: 63.97

Here, I am not rounding any values other than Total when submitting the form; without rounding the Total will be 63.963. So, doing this rounding only for Total and not for others creates issues. For some countries I need to use the precision 2, and others 3

Moreover, I would like to know if this is the correct way to store these values in DB.

Is there any rule like doing the rounding for each column (Charge, S-Tax, C-Tax, and Total)? or any rules for the precision & scale? OR should we convert this to integer?

If we go for integer, should we round it and convert to integer?

What would be the correct data we should store when we submit it? It would be great if someone could suggest, as this has been haunting for some time.

vendredi 1 décembre 2023

Map an activerecord array to avoid that two item with the same attribute are in a sequential position

I have an issue to solve.

I have an array of elements, and on each element I can call the method 'content.sponsored?' that return me true or false.

The items that return true are 2/3 every 20 elements and they are always in the first position.

I need to map this array to avoid consecutive 'true'.

For example

contents = [
  { id: 1, sponsored: true },
  { id: 2, sponsored: true },
  { id: 3, sponsored: false },
  { id: 4, sponsored: false },
  { id: 5, sponsored: false },
  { id: 6, sponsored: false }...
]

I need

contents = [
  { id: 1, sponsored: true },
  { id: 2, sponsored: false },
  { id: 3, sponsored: true },
  { id: 4, sponsored: false },
  { id: 5, sponsored: false },
  { id: 6, sponsored: false }...
]

Which is the most efficient way to map these elements?

jeudi 16 novembre 2023

Devise Registration Ruby on Rails - Migration Error: Duplicate column name

I'm encountering an issue while running a Rails migration that adds Devise to my Users table. The error message points to a duplicate column name, specifically "email." The migration file causing the problem is located at /Users/jaydenthelwell/pye-candles/pye-candles/db/migrate/20231115201715_add_devise_to_users.rb.

Here is the error:

`➜ pye-candles git:(master) ✗ rails db:migrate == 20231115201715 AddDeviseToUsers: migrating ================================= -- change_table(:users) rails aborted! StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: duplicate column name: email /Users/jaydenthelwell/pye-candles/pye-candles/db/migrate/20231115201715_add_devise_to_users.rb:7:in block in up' /Users/jaydenthelwell/pye-candles/pye-candles/db/migrate/20231115201715_add_devise_to_users.rb:5:in up'

Caused by: ActiveRecord::StatementInvalid: SQLite3::SQLException: duplicate column name: email /Users/jaydenthelwell/pye-candles/pye-candles/db/migrate/20231115201715_add_devise_to_users.rb:7:in block in up' /Users/jaydenthelwell/pye-candles/pye-candles/db/migrate/20231115201715_add_devise_to_users.rb:5:in up'

Caused by: SQLite3::SQLException: duplicate column name: email /Users/jaydenthelwell/pye-candles/pye-candles/db/migrate/20231115201715_add_devise_to_users.rb:7:in block in up' /Users/jaydenthelwell/pye-candles/pye-candles/db/migrate/20231115201715_add_devise_to_users.rb:5:in up' Tasks: TOP => db:migrate (See full trace by running task with --trace) ➜ pye-candles git:(master) ✗ `

Here's the relevant the migration file:

`# frozen_string_literal: true

class AddDeviseToUsers < ActiveRecord::Migration[7.0] def self.up change_table :users do |t| ## Database authenticatable t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: ""

  ## Recoverable
  t.string   :reset_password_token
  t.datetime :reset_password_sent_at

  ## Rememberable
  t.datetime :remember_created_at

  ## Trackable
  # t.integer  :sign_in_count, default: 0, null: false
  # t.datetime :current_sign_in_at
  # t.datetime :last_sign_in_at
  # t.string   :current_sign_in_ip
  # t.string   :last_sign_in_ip

  ## Confirmable
  # t.string   :confirmation_token
  # t.datetime :confirmed_at
  # t.datetime :confirmation_sent_at
  # t.string   :unconfirmed_email # Only if using reconfirmable

  ## Lockable
  # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
  # t.string   :unlock_token # Only if unlock strategy is :email or :both
  # t.datetime :locked_at


  # Uncomment below if timestamps were not included in your original model.
  # t.timestamps null: false
end

add_index :users, :email,                unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token,   unique: true
# add_index :users, :unlock_token,         unique: true

end

def self.down # By default, we don't want to make any assumption about how to roll back a migration when your # model already existed. Please edit below which fields you would like to remove in this migration. raise ActiveRecord::IrreversibleMigration end end

`

I deleted the User migration file as I thought this was causing the issue, the users table also has "email" but the problem persists.

lundi 13 novembre 2023

how to send data to sidekiq queue from ruby app

im new with sideqik and i want to test it for verify that sideqik receive data from a very simple ruby app. exist one method to send data easily?

This is my ruby app:

require "redis"
redis =Redis.new(host: "127.0.0.1", port: 6379)
redis.set("mykey", "hello world!")
redis.post("mykey")

i tried with this script, the connection with sideqik works but when i accessed in its webUI i cant see data. Thank you for help.

Overriding object_changes on paper trails to store name corresponding to change in IDs

For associations, I am assigning IDs from different model to my model and therefore IDs are being changed. Papertrail tracks those changes, and this is the state of my object_changes:

{
  "updated_at": [
    "2023-11-13T08:54:26.346Z",
    "2023-11-13T08:56:06.961Z"
  ],
  "paying_id": [
    "ID1",
    "ID1 new"
  ],
  "company_ids": [
    [
      "ID1",
      "ID2",
      "ID3",
      "ID4"
    ],
    [
      "ID1 new",
      "ID2 new",
      "ID3 new"
    ]
  ]
}

However, in my view for the audit logs, I do not want to display the IDs, but display the names corresponding to those IDs. Right now, I am using if loops to query the names and send to the view. But there must be a better way than this. The docs is also against overriding object_changes, but if object_changes is not overriden, then how?

What is the correct way to do this?

vendredi 3 novembre 2023

Why do I get NoMethodError: undefined method `rescue' for #

Ruby's Concurrent::Future was not catching the exceptions. So I copied the code from an article to add a rescue block. But now I got the error:

Caused by NoMethodError: undefined method `rescue' for #Concurrent::Future:0x0000000124764268

Here is the code:

executed_future = Concurrent::Future.execute do
            url = "#{endpoint}#{datum[:hierarchy_id]}#{valuation_date}"
            raise StandardError.new("Testing error!") # To test

            [...]
          end.rescue do | exception | # Adding this, will throw the error
            @exceptions << exception
            binding.pry # No activated
          end

What am I missing?

I expect to rescue exceptions in the Concurrent::Future block. Just like the article does.

mardi 31 octobre 2023

undefined method `to_model' for #

<%= form_with(model:[@single_room, @message] , remote: true, class: "d-flex" ) do |f| %> <%= f.text_field :body, id: 'chat-text', class: "form-control ", autocomplete: 'off' %> <%= f.submit data: { disable_with: false }, class: "btn btn-primary" %> <% end %>

why it is coming like this

lundi 30 octobre 2023

Mailgun Showing Variable Names as it is Ruby on Rails

I have a template field in my object in which i store the whole email template and store it like below "<p><span style=\"font-family: -apple-system, system-ui, &quot;Segoe UI&quot;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif;\">%recipient.email%<b><br></b></span><b>&nbsp;<br>&nbsp;</b><span style=\"font-family: -apple-system, system-ui, &quot;Segoe UI&quot;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif;\">%recipient.tier_name%</span></p>" in this %recipient.email% is my variable and it will changed by mailgun automatically but the issue is sometimes it does not reflect and appear as it is in the email with out changing its actaul value

example: If recipient.email = test@gmail.com but in email it is showing %recipient.email% instead of test@gmail.com

I want to apply the variable values instead of its variable names. example: If recipient.email = test@gmail.com but in email it is showing %recipient.email% instead of test@gmail.com

def self.send_emails(subject:, html:, to_emails:, recipient_variables: {}, force_send: false, sender_email)
payload = {
  from: sender_name(sender_email),
  subject:,
  html:,
  'recipient-variables': recipient_variables.to_json,
  'o:tag': [subject, tag]
}
esponse = RestClient.post(mailgun_api_url(sender_email), payload)

end

vendredi 27 octobre 2023

Error (Could not find the inverse association for profile_image_attachment (:record in ActiveStorage::Attachment)):

In my model/active_storage/attachment.rb file i had used this code

class ActiveStorage::Attachment < ApplicationRecord belongs_to :blob, class_name: "ActiveStorage::Blob" def self.ransackable_attributes(auth_object = nil) ["blob_id", "created_at", "id", "name", "record_id", "record_type"] end end "When creating Active Admin with Active Storage, I encountered a search error. To address this, I used defined the ransackable method in my model." in my model/user.rb i had used has_one_attached :profile_image when i open this link http://127.0.0.1:3000/users/1 it show this error unknown keywords: :class_name, :as, :inverse_of and when i open this link http://127.0.0.1:3000/admin it open successfullyenter image description here

i had used inverse of in my model/user.rb file , but it did't work i had go through all my schema file it generate activestorage of correctlly.

jeudi 26 octobre 2023

ActiveRecord::InverseOfAssociationNotFoundError in rails 7

Hii in my rails application when I going to open the profile page the following error comes My ruby version is "3.2.2" and my rails version is "7.0.8"

ActiveRecord::InverseOfAssociationNotFoundError in Users#show

Showing /home/nitish/Documents/Bestristey/app/views/users/_user_profile_image.html.erb where line #3 raised:

ActionView::Template::Error (Could not find the inverse association for profile_image_attachment (:record in ActiveStorage::Attachment)):

        1: <div id="profile_image">
        2:     <div>
        3:         <% if user.profile_image.attached? %>
        4:         <%= image_tag(user.profile_image, class: "d-block ui-w-80 " ) %>
        5:         <% else %>
        6:         <img src ="/assets/dummy profile.jpg" alt class="d-block ui-w-80 rounded-circle">

This is the code of my user model:-

class User < ApplicationRecord

      after_create :after_confirmation
  
      devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable, :trackable
            
      validates :username, presence: true, uniqueness: true

      has_one_attached :profile_image

      attr_accessor :login
  
      def login
        @login || self.username || self.email
      end
     end


And this is the code from my models/active_storage/attachment.rb file:-

`
class ActiveStorage::Attachment < ApplicationRecord

        belongs_to :blob, class_name: "ActiveStorage::Blob", inverse_of: :attachment

    
  
        def self.ransackable_attributes(auth_object = nil)
          ["blob_id", "created_at", "id", "name", "record_id", "record_type"]
        end
  
      end

I have tried of using :inverse_of in the users model has_one_attached association but then it gives argument error. I also tried some other stuffs also but still no any progress.

mercredi 25 octobre 2023

dyld[4255]: missing symbol on Apple M2

I am running ruby on rails project on my apple M2. Ruby version is 2.5.5. I have done setup using rosetta. After installing all the dependencies when i try to run the console i.e. rake c. I get this error

dyld[4255]: missing symbol called [1] 4255 abort rake c

I have tried removing the old ruby and starting this process from scratch. Have also installed brew using rosetta.

Does anyone know how to solve this?

lundi 23 octobre 2023

Calling a Static Method from a Controller and Updating instance of that class - Getting undefined method for AR::Association::HasOneAssociation

My Question:

What should the correct structure be? I have tried redesign this several times but keep getting tight-coupling issues.

Relevant Info:

I am writing a new endpoint for some third party software. It will receive a payload that I am then passing into a static method of my Subscription class. From there I want to do a look-up of the payload related subscription, establish an instance of it, then perform an update based off the rest of my information on my class. I am running into an error that is saying the following: undefined method update for ActiveRecording::Association::HasOneAssociation

EndPointController:

class Api::V2::EndpointController < Api::V5::BaseController
    def connect
        data = decode(request.body.read)
        Subscription.static_method(data)
    end
end

Subscription Model:

class Subscription < ActiveRecord::Base

    def self.static_method(data)
        @subscription = Subscription.find_by_id(data.subscription_id)
        @subscription.update(data)
    end
end

Subscription Controller:

class SubscriptionsController < ApplicationController
    def update
        #execute update
    end
end

how to debug gitlab-ce docker container?

My environment: osx14.0 rubymine gitlab-ce 16.4

I want to debug gitlab-ce remotelly with local rubymine on my mac. I expose 3000 in the docker container, but rubymine cannot debug it on 3000 port directly. I am more familiar to Java and PHP, but new to ruby thanks!

I tried to use rubymine connect to 3000 port on the docker container, but I failed

jeudi 19 octobre 2023

Update Database in Ruby on Rails version 7.11

Hello community I am new to ruby on rails, I have a problem with updating the database, when I try to update a record, all records are updated

this is my article_controller this is my router

I was reviewing the documentation and I saw that I do it similarly, I have searched for information on the internet and I can't find a solution

I want to update only one record by passing the id

mardi 3 octobre 2023

How to authenticate and access the Gmail API in Ruby without using OOB

How do I connect to the api without using oob since it is obsolete, I have been searching and I can't find any example. Alguna ayuda

These are the methods for OOB but I don't need to use them as they are deprecated.

type here
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'google/apis/gmail_v1'

# Constants for authentication
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze
APPLICATION_NAME = 'Your Gmail Application'
CLIENT_SECRETS_PATH = 'path/to/client_secrets.json'.freeze
CREDENTIALS_PATH = 'path/to/credentials.yaml'.freeze
SCOPE = Google::Apis::GmailV1::AUTH_SCOPE

# Configure authentication
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE)
credentials = authorizer.get_credentials('user_id', token_store)

Step 2: Credential Verification
In this step, we'll check if we already have stored credentials or if we need user authentication.

# Check if credentials exist or if user authentication is needed
if credentials.nil?
  url = authorizer.get_authorization_url(base_url: OOB_URI)
  puts 'Open the following URL in your browser and enter the authorization code:'
  puts url
  code = gets
  credentials = authorizer.get_and_store_credentials_from_code(
    user_id: 'user_id', code: code, base_url: OOB_URI, token_store: token_store
  )
end

jeudi 21 septembre 2023

i want to see server log file from browser in rails app button click

i have a make a deployment app , by clicking deployment button it deployed, now i want to see the log file like terminal show in browser

i try to read the log file using file read but when i start to read my application stop with this

Rendering deployments/show_log.html.erb within layouts/application
/home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/core_ext/string/output_safety.rb:350: [BUG] Segmentation fault at 0x00007f46a87f1000
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0123 p:---- s:0827 e:000826 CFUNC  :escapeHTML
c:0122 p:0036 s:0822 e:000821 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/core_ext/string/output_safety.rb:350
c:0121 p:0012 s:0814 e:000812 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/core_ext/string/output_safety.rb:216
c:0120 p:0016 s:0808 e:000807 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/buffers.rb:29
c:0119 p:0022 s:0803 e:000802 METHOD /home/syftet/development/trusteeze-saas/app/views/deployments/show_log.html.erb:2 [FINISH]
c:0118 p:---- s:0797 e:000796 CFUNC  :public_send
c:0117 p:0042 s:0790 e:000789 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/base.rb:244
c:0116 p:0025 s:0776 e:000775 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/template.rb:157
c:0115 p:0034 s:0773 e:000772 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/notifications.rb:208
c:0114 p:0024 s:0767 e:000766 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/template.rb:361
c:0113 p:0021 s:0762 e:000761 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/template.rb:155
c:0112 p:0013 s:0751 e:000750 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/template_renderer.rb:65
c:0111 p:0010 s:0748 e:000747 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/notifications.rb:206
c:0110 p:0022 s:0745 e:000744 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/notifications/instrumenter.rb:24
c:0109 p:0023 s:0737 e:000736 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/notifications.rb:206
c:0108 p:0033 s:0731 e:000730 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/template_renderer.rb:60
c:0107 p:0011 s:0727 e:000724 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/template_renderer.rb:75
c:0106 p:0010 s:0722 e:000721 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/notifications.rb:206
c:0105 p:0022 s:0719 e:000718 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/notifications/instrumenter.rb:24
c:0104 p:0023 s:0711 e:000710 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/notifications.rb:206
c:0103 p:0050 s:0705 e:000704 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/template_renderer.rb:74
c:0102 p:0012 s:0695 e:000694 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/template_renderer.rb:59
c:0101 p:0048 s:0687 e:000686 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/template_renderer.rb:11
c:0100 p:0020 s:0680 e:000679 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/renderer.rb:61
c:0099 p:0023 s:0674 e:000673 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/renderer/renderer.rb:29
c:0098 p:0009 s:0668 e:000667 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/rendering.rb:117
c:0097 p:0089 s:0664 e:000663 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/base.rb:270
c:0096 p:0051 s:0656 e:000655 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/rendering.rb:116
c:0095 p:0044 s:0646 e:000645 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/streaming.rb:216
c:0094 p:0015 s:0641 e:000640 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionview-7.0.5/lib/action_view/rendering.rb:103
c:0093 p:0010 s:0636 e:000635 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/rendering.rb:158
c:0092 p:0015 s:0631 e:000630 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/renderers.rb:141
c:0091 p:0018 s:0626 e:000625 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/abstract_controller/rendering.rb:27
c:0090 p:0033 s:0618 e:000617 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/rendering.rb:139
c:0089 p:0010 s:0613 e:000612 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/instrumentation.rb:22
c:0088 p:0028 s:0610 e:000609 METHOD /home/syftet/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/benchmark.rb:308
c:0087 p:0009 s:0605 e:000603 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/core_ext/benchmark.rb:14
c:0086 p:0013 s:0599 e:000598 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/instrumentation.rb:22
c:0085 p:0002 s:0596 e:000595 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/instrumentation.rb:91
c:0084 p:0066 s:0592 e:000591 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/activerecord-7.0.5/lib/active_record/railties/controller_runtime.rb:34
c:0083 p:0008 s:0585 e:000583 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/instrumentation.rb:21
c:0082 p:0021 s:0578 e:000577 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/implicit_render.rb:35
c:0081 p:0020 s:0573 e:000572 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/basic_implicit_render.rb:7
c:0080 p:0011 s:0566 e:000565 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/abstract_controller/base.rb:215
c:0079 p:0022 s:0560 e:000559 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/action_controller/metal/rendering.rb:165
c:0078 p:0009 s:0555 e:000554 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actionpack-7.0.5/lib/abstract_controller/callbacks.rb:234
c:0077 p:0048 s:0552 E:002550 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/activesupport-7.0.5/lib/active_support/callbacks.rb:118
c:0076 p:0013 s:0542 E:002590 METHOD /home/syftet/.rvm/gems/ruby-3.0.0/gems/actiontext-7.0.5/lib/action_text/rendering.rb:20
c:0075 p:0021 s:0536 E:0025d0 BLOCK  /home/syftet/.rvm/gems/ruby-3.0.0/gems/actiontext-7.0.5/lib/action_text/engine.rb:69 [FINISH]
c:0074 p:---- s:0531 e:000530 CFUNC  :instance_exec

mardi 19 septembre 2023

Insert many json file inside one document in mongoDB

i have a question: but how can i insert many json files inside one document collection? I have a ruby script connected with mongoDB which generate json files for each ID product. In mongo i should want a structure like this:

Id(document's name) : {

many json for same ID

} 

how can i get this structure in ruby?

DB's name is "test_db" and collection's name is "test_coll"

mardi 12 septembre 2023

URI Error with RUBY when trying to run an application

so for some reason my ruby encounter this error when I try to create a new application on Windows 10:

rails aborted! URI::InvalidURIError: bad URI(is not URI?): C:\Ruby\bin;C:\sqlite; C:/Users/Lies/demo42/Rakefile:6:in <main>' <internal:C:/Ruby/lib/ruby/site_ruby/3.2.0/rubygems/core_ext/kernel_require.rb>:38:in require' <internal:C:/Ruby/lib/ruby/site_ruby/3.2.0/rubygems/core_ext/kernel_require.rb>:38:in require' bin/rails:4:in <main>' (See full trace by running task with --trace) rails turbo:install stimulus:install rails aborted! URI::InvalidURIError: bad URI(is not URI?): C:\Ruby\bin;C:\sqlite; C:/Users/Lies/demo42/Rakefile:6:in <main>' <internal:C:/Ruby/lib/ruby/site_ruby/3.2.0/rubygems/core_ext/kernel_require.rb>:38:in require' <internal:C:/Ruby/lib/ruby/site_ruby/3.2.0/rubygems/core_ext/kernel_require.rb>:38:in require' bin/rails:4:in <main>' (See full trace by running task with --trace)

I've searched everywhere on Google and so far I've try reinstalling twice, changing the path varible to C:\ruby and adding it to path and DATABASE variable.

My ruby, rails is on the latest version.

So far running "rails new demo --minimal" is the only one that work in helping me creating the application but when I try to run the server it show this: localhost:3000 output

Has anyone encountered this and figure out how to fix? I asked my professor, and it also picked his brain trying to figure out.

Thank you!

jeudi 7 septembre 2023

Ruby on Rails - Double Render Error - Redirect and Return

Error: AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".)

On update, model checks for template.exists?, if true, download the report AND redirect to parent object. Else, just redirect.

I'm using 'and return' on the tangential side of the 'if' statement, so why isn't that working as expected?

def update
  template = resource.check_changes(params[:well_master])
  paramString = resource.to_json

  update! do |format|
    if resource.errors.present?
      return render :edit
    else
      if template != ''
        generateWellLetter(template, 'Rpt_Farm_Name', paramString) 
      else
        rec = resource.PERMIT
        format.html { redirect_to admin_well_master_path(rec) }
      end
    end
  end
 end
end

def generateWellLetter(template, letterName, params)
    @URL = "#{ENV["API_HOST"]}/api/Document/Generate/#{template}"
    response = HTTParty.post(@URL,
                             :body => params,
                             :headers => { "Content-Type" => "application/json" })

Zip::InputStream.open(StringIO.new(response)) do |io|
  while entry = io.get_next_entry
    report = io.read
    send_data report, :filename => letterName + '.docx', :type => 'docx'
  end
end

respond_to do |format|
  rec = resource.PERMIT
  format.html { redirect_to admin_well_master_path(rec) } and return
end

end

mercredi 6 septembre 2023

Ruby 1.8.7 on Rails 2.3.5 application rendering speed slows down overtime

Previously, the application worked on a shared hosting without a docker container and the performance was good. After transferring to a dedicated server, the application was made through a docker container and a performance problem appeared. The developer assured that there was a problem with the old Ruby, but if before everything worked within the normal range, now the application restarts every 6 hours trough cron (docker-compose down) to maintain normal speed. Application handles concurrency poorly.

The main problem is that initial rendering speed is:

Processing CatalogController#index (for 127.0.0.1 at 2023-09-06 19:22:06) [GET] Parameters: {"controller"=>"catalog", "language"=>"ru", "action"=>"index"} Rendering template within layouts/main Rendering catalog/index Completed in 330ms (View: 300, DB: 30) | 200 OK [http://localhost/]

Than after 300 requests it slows to:

Processing CatalogController#index (for 127.0.0.1 at 2023-09-06 19:22:06) [GET] Parameters: {"controller"=>"catalog", "language"=>"ru", "action"=>"index"} Rendering template within layouts/main Rendering catalog/index Completed in 1266ms (View: 1233, DB: 37) | 200 OK [http://localhost/]

When I try to use ab -n 100 http://localhost:3000/ it shows result like:

Concurrency Level:      1
Time taken for tests:   33.883 seconds
Complete requests:      100
Failed requests:        0
Total transferred:      6796500 bytes
HTML transferred:       6764800 bytes
Requests per second:    2.95 [#/sec] (mean)
Time per request:       338.831 [ms] (mean)
Time per request:       338.831 [ms] (mean, across all concurrent requests)
Transfer rate:          195.89 [Kbytes/sec] received

Code in Dockerfile that builds application:

FROM centos:7
SHELL ["/bin/bash", "-c"] 

RUN yum update -y && yum -y install gpg curl which wget ImageMagick-devel mysql mysql-devel libxml2-devel libxslt libxslt-devel

#Install RVM
RUN gpg --keyserver keyserver.ubuntu.com --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
RUN \curl -sSL https://get.rvm.io | bash -s stable

#Install Ruby
RUN source /etc/profile.d/rvm.sh && rvm install 1.8.7

#Install Ruby Gems
RUN source /etc/profile.d/rvm.sh && rvm use 1.8.7 && gem install -v=2.3.5 rails && gem install bundler -v=1.3.5 && gem install rubygems-update -v 1.3.7 && update_rubygems --version=1.3.7 && gem install mime-types -v=1.17.2 && gem install russian -v=0.2.7 && gem install httparty -v=0.7.2 && gem install mini_mime -v=1.1.2 && gem install yandex_inflect -v=0.1.0 && PATH="/app/ImageMagick-6.8.0-10/Magick++/bin:$PATH" gem install rmagick -v=2.13.2 && gem install mechanize -v=0.8.5 && gem install geoip -v 1.1.2 && gem install rdoc -v=3.9.2 && gem install mysql -v=2.9.1 && gem install nokogiri -v=1.4.4 && gem install daemons -v=1.1.0 && gem install thin -v=1.7.0

WORKDIR /app

RUN mkdir /app/tmp

CMD source /etc/profile.d/rvm.sh && rvm use 1.8.7 && script/server thin -p 3000 -e production

Maybe someone knows what can cause such a behavior?

I have tried to install thin server instead of a WebBrick but it didn't resolve the problem. And only solution for now is docker-compose down command but it restarts application entirely for almost 16 seconds. Lookes through a code and didn't find code that can slow down the application.

Possible solutions to the problem:

  1. Correctly configure the docker container (the application did not work on docker before, so the problem may be in its settings)
  2. Install unicorn or passenger (it worked on webrick during the transfer, then transferred to thin, but it didn't help much)
  3. Install some additional gems (before, more gems were installed on the hosting, but now only the most necessary ones).
  4. It is necessary to transfer the application to a new version of Ruby on Rails (if there is no other way out, then you have to do it)

lundi 4 septembre 2023

Move static asset folder of rails application to S3 Bucket

i want to cdn my static asset of rails application,i have gone through the AWS documentation for it and have created my distribution also now i want to ask how i can move my static asset folder to S3 bucket so that i can cdn them? I am following this link for it text

dimanche 27 août 2023

Updating Record in a after commit call back will trigger infinite calls again and again?

for example

class Order < ApplicationRecord
  after_commit :update_status

  def update_status
     self.update_attribute(:status, 'completed')  
  end
end

im wondering, how this will be handled in rails?

Is it tirgger again and again?

because in some scenarios, its triggering but in some scenrios its not.

samedi 26 août 2023

ActionView::Template::Error (wrong number of arguments (given 2, expected 1))

I am upgrading from Rails 5.2 to Rails 7. After running the server with rails s when I go to any routes, it gives me Completed 500 Internal Server Error

ActionView::Template::Error (wrong number of arguments (given 2, expected 1)):

<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>

<%= stylesheet_link_tag    'eye-candy', media: 'all', 'data-turbolinks-track' => true %>

<%= stylesheet_link_tag    'charts', media: 'all', 'data-turbolinks-track' => true %>

app/views/layouts/application.html.erb:19 app/controllers/application_controller.rb:93:in `track'

I tried removing arguments but stylesheet_link_tag is not even taking a single argument.

vendredi 25 août 2023

Error while installing any specific version of ruby through rvm in mac m1

I am facing an issue while installing any version of ruby through rvm in Mac m1. Globally, I have installed ruby version 3.0.0 but for a project, I needed version 3.0.2 but it gives me the following error, no matter how many different versions I try to install the error is the same:

Error running '__rvm_make -j8',

please read /Users/hammadahmad/.rvm/log/1692909928_ruby-2.7.4/make.log

There has been an error while running the make. Halting the installation.

I have tried reinstalling RVM but still no solution. I even tried to do it when rbenv but it gives me other issues like incompatible environment bootsnap.

I tried everything but nothing worked so I'm tired of this.
I want it to work properly and by properly I want to install any version of ruby with the ruby version manager as it does on any other system, The error it is showing is not encountered to anyone else and if it does then there is no guidance about it.

mercredi 23 août 2023

No unique index found for id

I have faced an error "No unique index found for id" while trying to use Upsert all. But isn't ID a unique index by default? Initially we have created our application in rails 3 and now we have migrated it to rails 6. Is this issue related to the migration?

I have added the below migration and it works fine

def change add_index :order_lists, :id, unique: true, algorithm: :concurrently end

mardi 22 août 2023

Tryin to get Users to log in to Microsoft Active directory on my rails app using Omniauth gem

i keep getting this from the console

Started POST "/auth/microsoft_graph" for ::1 at 2023-08-22 11:57:05 +0100
D, [2023-08-22T11:57:05.241303 #14844] DEBUG -- omniauth: (microsoft_graph) Request phase initiated.

without any further response or action on the console. i am not receiving any tokens and also not being redirected to sign in like I should. I have tried it with omniauth-facebook gem to be sure and it's the same response. I believe I'm missing a step but I don't know what it is

i have installed these gem

gem 'omniauth-oauth2'
gem 'omniauth-microsoft_graph'
gem "omniauth-rails_csrf_protection"

then I created this button to sign in:

<%= button_to "Connect microsoft_graph", "/auth/microsoft_graph", method: :post, class: "mt-4 p-2 btn bg-blue-400 rounded" %>

this is the omniauth.rb located in the initializers folder:

Rails.application.config.middleware.use OmniAuth::Builder do
   provider :microsoft_graph, "a47d3c7d-xxxxxxxx", "YOV8Q~9z~xxxxxxxxxxxx"
end

I also created the route in the route.rb file

get "/auth/microsoft_graph/callback", to: "omniauth_callbacks#microsoft"

finally created the controller file and action and microsoft_account model referencing user

class OmniauthCallbacksController < applicationController
    def microsoft
        Rails.logger.info auth
        # render plain: "success"
        current_user.microsoft_accounts.create(

            name: auth.info.name,
            username: auth.info.name,
            token: auth.credentials.token,
            secret: auth.credentials.secret

        )

        redirect_to root_path, notice: "Successfully connected your account"
    end
 def auth
        request.env['omniauth.auth']
    end

lundi 7 août 2023

"bundle install" CA certificates

I am attempting to create a github pages website, and it requires me to do

bundle install

I have tried this, and this is the error message I'm getting:

Fetching source index from https://rubygems.org/
There is a chance you are experiencing a man-in-the-middle attack, but most likely your system doesn't have the CA certificates needed for verification. For information about OpenSSL certificates, see
https://railsapps.github.com/openssl-certificate-verify-failed.html. To connect without using SSL, edit your Gemfile sources and change 'https' to 'http'

I am wary of using 'http' to solve this issue. I have tried downloading the SSL cert file and have followed this guide, but unfortunately am unable to solve the issue: https://bundler.io/guides/rubygems_tls_ssl_troubleshooting_guide.html

These are the two commands I have run:

sudo cp ~/GlobalSignRootCA_R3.pem /usr/lib/ruby/vendor_ruby/rubygems/ssl_certs/rubygems.org
sudo cp ~/GlobalSignRootCA_R3.pem /usr/lib/ruby/3.0.0/rubygems/ssl_certs

Is there anything else I can do? I've looked at the other StackExchange posts, and it seems like this is an old but resolved issue, so I'm at a loss. I am using a Linux machine. Thank you!

samedi 5 août 2023

Looking for guidance for new learning [closed]

I want to learn programming. what do you think which will be better option to explore for a person who is purely from project management background and have basic understanding of just HTML/CSS/BOOTSTRAP and looking to learn more.

  1. Node JS
  2. Angular
  3. Ruby on rails.

I hope in details roadmap for all stacks will help me to better understand this.

lundi 31 juillet 2023

Can't able to create a simple login page in Rails

routes.rb

Rails.application.routes.draw do
  get '/login' , to: 'sessions#new'
  post '/login', to: "sessions#create"
end

sessions_controller.rb

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      redirect_to user
    else
      flash.now[:danger]='Invalid login id'
      render 'new'
    end
  end

  def destroy
    log_out
    redirect_to root_url
  end
end

views/sessions/new.html.erb

<%= form_with url: login_path, local: true do |form| %>
    <%= form.label :email %>
    <%= form.email_field :email %>
    <%= form.label :password %>
    <%= form.password_field :password %>
    <%= form.submit "LogIn"%>
<% end %>

Error: NoMethodError in SessionsController#create undefined method `[]' for nil:NilClass Extracted source (around line #6): 5.def create 6. user = User.find_by(email: params[:session][:email].downcase) 7. if user && user.authenticate(params[:session][:password])

I still can't understand why is this happening.

tried everything to solve on my own but can't.

mercredi 26 juillet 2023

I'm working on implementing a search feature in my Ruby on Rails with Diacritic Search Matching Exact Word

 if params[:name]
      name_normalized = params.unicode_normalize(:nfkd).gsub("_", "\\_")
      brands = brands.where("name LIKE ?", "%#{name_normalized}%")
 end

When I search for the diacritic character "š" in the database, the search query does not return any results, even though there is a record with the name "Tešt" containing that character.

If I modify the query to make it diacritic, it returns results like "testing," "Test," "Tešt," and "demo_Test" when searching for "š." However, my desired result is only the exact match "Tešt" because I was specifically searching for this particular word.

Despite all this, the search still doesn't fetch the desired results. I suspect there might be an issue with the query or how I'm handling the search term.

I have used .gsub("_", "\\_") to handle cases involving underscores in my query, and it is working as expected. If I use it in the query alone, it functions correctly.

Can anyone please guide me on how to implement a diacritic search properly using Ruby on Rails and SQL? Any insights or suggestions would be greatly appreciated. Thank you!

mardi 25 juillet 2023

Ruby Datetime Error no implicit conversion of nil into String

I am getting the error "TypeError: no implicit conversion of nil into String" in Datetime method (ruby) and I wonder why my code is not working accordingly if I already have exception implemented. Any explanation about this or how to get rid of it?

      def get_parsed_datetime(raw_payload)
        parse_datetime(raw_payload[:datetime])
      rescue ArgumentError
        raise Base::UnprocessableContentError, I18n.t('invalid_datetime_error')
      end

      def parse_datetime(datetime_value)
        {
          :date => Date.parse(datetime_value).strftime('%d/%m/%Y'),
          :hour => Time.parse(datetime_value).hour
        }
      end

how to delete a record and go to delete page in rails 7 after installing ujs?

I am using Rails 7 and also install ujs but whenever i click on delete button Get request call rather than destroy request and i go to view record page rather then delete employee page. This is the code of delete link:

<%= link_to "Delete", employee_path(employee), method: :delete, class: "btn btn-danger", data: { confirm: "Are You sure to delete this employee" } %>

and this is the code of delete action from controller file:

def destroy
    @employee = Employee.find(params[:id])
    if @employee.destroy
      redirect_to employees_path, notice: "Employee has been deleted"
    end
  end

samedi 22 juillet 2023

Working on ruby on rails and caught in a situation where i can't determine why is it doing like that

I am working on a project called foodlog where the person can enter the food they eating the number of calories ,protiens, carbs, fats etc. The issue i am facing is if i create 2 entries in it , the display will show 4 of them if i place 3 entries in it, then 9 and so on . it's just reshowing the entries after each iteration and i can't determine why's that.

I have uploaded it on my github if anyone has time pls help. https://github.com/s-chuck/git_test in my opinion the problem is most probably on views folder and in views/_entry.html.erb file.

i have tried doing everything and i am expecting the entries should only be showed once in my website.

dimanche 16 juillet 2023

active admin gem error message just following the instructions

I am using ruby 3.1.3, rails 7.0.5 and activeadmin 3.0.

I just followed the installation instructions from the activeadmin website, but I got the following error:

ActionView::Template::Error (Ransack needs AdminUser attributes explicitly allowlisted as
searchable. Define a `ransackable_attributes` class method in your `AdminUser`
model, watching out for items you DON'T want searchable (for
example, `encrypted_password`, `password_reset_token`, `owner` or
other sensitive information). You can use the following as a base:

ruby
class AdminUser < ApplicationRecord

  # ...

  def self.ransackable_attributes(auth_object = nil)
    ["created_at", "email", "encrypted_password", "id", "remember_created_at", "reset_password_sent_at", "reset_password_token", "updated_at"]
  end

  # ...

end

):
    1: # frozen_string_literal: true
    2: insert_tag renderer_for(:index)

I tried to follow the instructions but I got the same error but now the array inside of the function is empty.

vendredi 14 juillet 2023

Trying to install Ruby 3.2.2 but keep getting error during installation

Please bear with me as this is my first time coding with Ruby, but I've been trying to install it for a while now but each time I keep getting the following error. Does anyone have any advice on how to fix this? I am currently on MacOS Ventura. picture of the error message in my terminal

Datatables buttons (export to excel) not displaying - Javascript /Ruby

Here I'm trying to add default excel export functionality for my JS project,

in profiles.js I have following code,

initDataTable({
    tableId: "#profilesStatusTable",
    orderVal: 1,
    sortingDirection: "asc",
    targetsVal: [0, 7],
    dom : 'Bfrtip',
        buttons : [ {
            extend: 'excel',
            text: 'Export To Excel'
        } ]
  });

      //Existing code for filter purpose
  $("#organizationFilterDropdown").dropdown();

  
  $("#organizationFilterDropdown").dropdown({
    onChange: function(value, text, $choice) {
      if (value === "Organisation") {
        // Reset option selected
        resetTableRecords(); // Call the function to reset the table records
      } else {
        var selectedOrganizationId = value;
        console.log(selectedOrganizationId);
  
        var profilesStatusTable = $("#profilesStatusTable").DataTable();
  
        profilesStatusTable.column(5).search(selectedOrganizationId).draw();
        
      }
    }
  });

But I cannot see any buttons , I also tried applying following in order where the table is implemented _status_table.html.erb,

<table>
  //code for table 
</table>



<link rel="stylesheet" type="text/css"  
href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
  <link rel="stylesheet" type="text/css"  
href="https://cdn.datatables.net/buttons/1.4.0/css/buttons.dataTables.min.css" />
  
<script type="text/javascript" 
src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script> 
<script type="text/javascript" 
src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" 
src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>

jeudi 6 juillet 2023

How to add alt-text to images attached to model via Cloudinary Active Storage?

I'm working on a project that has_many_photos_attached to a Project model. I'm attaching photos to each new instance of Project via Cloudinary Active Storage in my Seeds like so: file = URI.open("URL_TO_PHOTO") project.photos.attach(io: file, filename: "PHOTO.png", content_type: "image/png")

When I want to display the photo(s), I do the following: <% @project.photos.each do |photo| %> <%= cl_image_tag photo.key %> <% end %>

I want to be sure that my site is accessible, so I want to add 'alt-text' to all my images. However, I'm not sure where this can be done - ideally I would add the alt text when I attach the photo in the seeds.

I'm using Ruby and Ruby on Rails.

Anyone have any ideas?

I've tried adding it simply here:

<% @project.photos.each do |photo| %> <%= cl_image_tag photo.key alt="alt text goes here" %> <% end %>

but received the following error from rails: "wrong number of arguments (given 1, expected 0)"

mardi 4 juillet 2023

Difficulties to create in database with cocookn / nested form

Good morning

I've been trying to save the content of a nested form in a database for a while now. I have a main form dependent on the Supplier model, and I have another SupplierRestaurantDelivery model which is there to define A delivery_day = day on which the restaurant can be delivered An order_day = day for which you must order to be delivered on delivery_day (display via javascript if delivery_day is checked) A max_hour_order = valid for all delivery_day

The purpose of the SupplierRestaurantDelivery model is to be able to calculate the possible delivery days for a restaurant.

Here are my three models:

class Supplier < ApplicationRecord
  has_many :ingredients
  has_many :supplier_orders
  has_many :supplier_restaurant_deliveries, inverse_of: :supplier
  accepts_nested_attributes_for :supplier_restaurant_deliveries, reject_if: :all_blank, allow_destroy: true

  validates :name, uniqueness: { case_sensitive: false }
  validates :franco, presence: true, numericality: { greater_than: 0 }
end

class SupplierRestaurantDelivery < ApplicationRecord
  belongs_to :restaurant, inverse_of: :supplier_restaurant_deliveries
  belongs_to :supplier, polymorphic: true
end

class Restaurant < ApplicationRecord
  belongs_to :company
  has_many :supplier_orders, dependent: :destroy
  has_many :user_restaurants
  has_many :users, through: :user_restaurants
  has_many :supplier_restaurant_deliveries
end

Here is my controller:

class SuppliersController < ApplicationController
  def index
    @suppliers = policy_scope(Supplier)
  end

  def new
    @supplier = Supplier.new
    @supplier.supplier_restaurant_deliveries.build
    authorize @supplier
  end

  def create
    @supplier = Supplier.new(supplier_params)
    puts "=======>>>>>  Create supplier"
    # @restaurant_id = current_user.current_restaurant_id
    puts "=======>>>>>  ID restaurant #{@restaurant_id}"
    @supplier.restaurant_id = current_user.current_restaurant_id
    # @supplier.update(restaurant_id: @restaurant_id)
    puts "=======>>>>>  errors :  #{@supplier.errors.full_messages}"
    puts "=======>>>>>  Restaurant added to :  #{@supplier}"

    if @supplier.save
      puts @supplier.errors.full_messages
      puts "=======>>>>>  I just pass @supplier.save "
      create_delivery_entries
      puts "=======>>>>> I just pass create_delivery_entries "

      redirect_to suppliers_path, notice: "Supplier was successfully created."
    else
      puts @supplier.errors.full_messages
      render :new, status: :unprocessable_entity
    end
    authorize @supplier
  end

  def create_delivery_entries
    delivery_days = params[:supplier][:supplier_restaurant_deliveries_attributes]["0"][:delivery_day] # Les jours de livraison sélectionnés
    order_days = params[:supplier][:supplier_restaurant_deliveries] # Les jours de commande pour chaque entrée
    puts "=======>>>>>  Delivery Days: #{delivery_days.inspect}"
    puts "=======>>>>>  Order Days: #{order_days.inspect}"

    delivery_days.each_with_index do |selected, index|
      day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][index]
      puts "Day: #{day}, Selected: #{selected}"
      puts "=======>>>>>  index: #{index} // day: #{selected}"
      next unless order_days[index].present? # Ignorer l'itération si order_days[index] est nil

      order_day = order_days[index][:order_day]
      puts "=======>>>>>  order day: #{order_day}"
      @supplier.supplier_restaurant_deliveries.create(delivery_day: day, order_day: order_day, supplier_type: 'Supplier')
      puts "=======>>>>>  created ... "
    end
  end


  def edit
    @supplier = Supplier.find(params[:id])
    authorize @supplier
  end

  def update
    @supplier = Supplier.find(params[:id])
    @supplier.update(supplier_params)
    if @supplier.save
      redirect_to suppliers_path
    else
      render :edit, status: :unprocessable_entity
    end
    authorize @supplier
  end

  def destroy
    @supplier = Supplier.find(params[:id])
    if @supplier.destroy
      flash[:notice] = "Le supplier a été supprimé avec succès."
    else
      flash[:error] = "Une erreur s'est produite lors de la suppression du supplier."
    end
    authorize @supplier
  end

  private

  def supplier_params
    params.require(:supplier).permit(
      :name,
      :address,
      :zip_code,
      :city, :phone,
      :franco,
      supplier_restaurant_delivery_attributes: [
        :id,
        :order_day,
        :max_hour_order,
        :_destroy,
        delivery_day: []
      ]
    )
  end
end

Forms :



<div class="container">
  <%= simple_form_for(supplier) do |f| %>
  <%= f.input :name, input_html: { class: "form-control" } %>
  <%= f.input :address, input_html: { class: "form-control" } %>
  <%= f.input :zip_code, input_html: { class: "form-control" } %>
  <%= f.input :city, input_html: { class: "form-control" } %>
  <%= f.input :phone, input_html: { class: "form-control" } %>
  <%= f.input :franco, input_html: { class: "form-control" } %>

  <div id="supplier_restaurant_deliveries">
    <%= f.fields_for :supplier_restaurant_deliveries do |delivery_fields| %>
      <%= render 'supplier_restaurant_delivery_fields', f: delivery_fields %>
    <% end %>
  </div>


    <%= f.button :submit, class: 'btn btn-primary' %>
<% end %>
</div>


Nested form :

  <div class="nested-fields">
    <%= f.input :max_hour_order, as: :string, input_html: { class: 'timepicker', placeholder: 'HH:MM', value: '' } %>
    <table class=" table table-striped table-hover" data-controller="supplier-delivery-options" >
      <thead>
        <tr>
          <th scope="col">Delivered?</th>
          <th scope="col">Order day</th>
        </tr>
      </thead>
        <tbody>
      <% ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'].each do |day| %>
          <tr>
            <td>
              <div class="form-check form-switch">
                <% checkbox_id = "flexSwitchCheckDefault_#{day.downcase}" %>
                <%= f.check_box :delivery_day,
                              class: 'form-check-input', type: 'checkbox', role: 'switch', id: checkbox_id,
                              data: {
                                action: "change->supplier-delivery-options#select",
                                check: day.downcase
                              },
                              multiple: true,
                              label: false %>
                <label class="form-check-label" for="<%= checkbox_id %>"><%= day %></label>
              </div>
            </td>
            <td>
              <%= f.input :order_day,
                                    label: false,
                                    collection: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                                    input_html: { disabled: true, data: { list: "#{day}" }, name: "supplier[supplier_restaurant_deliveries][][order_day]" } %>
            </td>
          </tr>
        </tbody>
      <% end %>
    </table>

</div>

I see it's stuck in the settings. If I put supplier_restaurant_deliveries_attributes, it blocks at @supplier.save If I put supplier_restaurant_delivery_attributes, then it goes much further. We can observe in the console what is blocking. Another element that challenges me in this console: why do I have an array of 8 elements returned for the 7 days when I only announce the 7 days of the week?

I selected my example in delivery day: wednesday and order_day: Tuesday, as well as delivery_day: saturday and order_day: friday

Console view :

Started POST "/suppliers" for 127.0.0.1 at 2023-07-04 10:08:50 +0200
Processing by SuppliersController#create as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "supplier"=>{"name"=>"test 30", "address"=>"", "zip_code"=>"", "city"=>"", "phone"=>"", "franco"=>"150", "supplier_restaurant_deliveries_attributes"=>{"0"=>{"max_hour_order"=>"15", "delivery_day"=>["0", "0", "0", "1", "0", "0", "0", "1", "0"]}}, "supplier_restaurant_deliveries"=>[{"order_day"=>"Tuesday"}, {"order_day"=>"Friday"}]}, "commit"=>"Create Supplier"}
  User Load (0.9ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
Unpermitted parameters: :supplier_restaurant_deliveries_attributes, :supplier_restaurant_deliveries. Context: { controller: SuppliersController, action: create, request: #<ActionDispatch::Request:0x00007fbd78012100>, params: {"authenticity_token"=>"[FILTERED]", "supplier"=>{"name"=>"test 30", "address"=>"", "zip_code"=>"", "city"=>"", "phone"=>"", "franco"=>"150", "supplier_restaurant_deliveries_attributes"=>{"0"=>{"max_hour_order"=>"15", "delivery_day"=>["0", "0", "0", "1", "0", "0", "0", "1", "0"]}}, "supplier_restaurant_deliveries"=>[{"order_day"=>"Tuesday"}, {"order_day"=>"Friday"}]}, "commit"=>"Create Supplier", "controller"=>"suppliers", "action"=>"create"} }
=======>>>>>  Create supplier
=======>>>>>  ID restaurant
=======>>>>>  errors :  []
=======>>>>>  Restaurant added to :  #<Supplier:0x00007fbd233e8e78>
  TRANSACTION (0.9ms)  BEGIN
  ↳ app/controllers/suppliers_controller.rb:22:in `create'
  Supplier Exists? (9.2ms)  SELECT 1 AS one FROM "suppliers" WHERE LOWER("suppliers"."name") = LOWER($1) LIMIT $2  [["name", "test 30"], ["LIMIT", 1]]
  ↳ app/controllers/suppliers_controller.rb:22:in `create'
  Supplier Create (9.8ms)  INSERT INTO "suppliers" ("name", "address", "zip_code", "city", "phone", "franco", "created_at", "updated_at", "restaurant_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"  [["name", "test 30"], ["address", ""], ["zip_code", nil], ["city", ""], ["phone", ""], ["franco", "150"], ["created_at", "2023-07-04 08:08:50.636762"], ["updated_at", "2023-07-04 08:08:50.636762"], ["restaurant_id", 2]]
  ↳ app/controllers/suppliers_controller.rb:22:in `create'
  TRANSACTION (3.7ms)  COMMIT
  ↳ app/controllers/suppliers_controller.rb:22:in `create'
=======>>>>>  I just pass @supplier.save
=======>>>>>  Delivery Days: ["0", "0", "0", "1", "0", "0", "0", "1", "0"]
=======>>>>>  Order Days: [#<ActionController::Parameters {"order_day"=>"Tuesday"} permitted: false>, #<ActionController::Parameters {"order_day"=>"Friday"} permitted: false>]
Day: Monday, Selected: 0
=======>>>>>  index: 0 // day: 0
=======>>>>>  order day: Tuesday
=======>>>>>  created ...
Day: Tuesday, Selected: 0
=======>>>>>  index: 1 // day: 0
=======>>>>>  order day: Friday
=======>>>>>  created ...
Day: Wednesday, Selected: 0
=======>>>>>  index: 2 // day: 0
Day: Thursday, Selected: 1
=======>>>>>  index: 3 // day: 1
Day: Friday, Selected: 0
=======>>>>>  index: 4 // day: 0
Day: Saturday, Selected: 0
=======>>>>>  index: 5 // day: 0
Day: Sunday, Selected: 0
=======>>>>>  index: 6 // day: 0
Day: , Selected: 1
=======>>>>>  index: 7 // day: 1
Day: , Selected: 0
=======>>>>>  index: 8 // day: 0
=======>>>>> I just pass create_delivery_entries
Redirected to http://localhost:3000/suppliers
Completed 302 Found in 64ms (ActiveRecord: 31.5ms | Allocations: 9494)


Started GET "/suppliers" for 127.0.0.1 at 2023-07-04 10:08:50 +0200
Processing by SuppliersController#index as TURBO_STREAM
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendering layout /home/quentinvandenbulcke/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/turbo-rails-1.4.0/app/views/layouts/turbo_rails/frame.html.erb
  Rendering suppliers/index.html.erb within layouts/turbo_rails/frame
  Supplier Load (0.9ms)  SELECT "suppliers".* FROM "suppliers"
  ↳ app/views/suppliers/index.html.erb:25
  Rendered suppliers/index.html.erb within layouts/turbo_rails/frame (Duration: 9.7ms | Allocations: 2408)
  Rendered layout /home/quentinvandenbulcke/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/turbo-rails-1.4.0/app/views/layouts/turbo_rails/frame.html.erb (Duration: 11.5ms | Allocations: 2633)
Completed 200 OK in 20ms (Views: 12.7ms | ActiveRecord: 1.5ms | Allocations: 4701)

Thanks a lot for your help

dimanche 2 juillet 2023

Gem doesn't work when using js importmap tag but does work with js include tag. Is there a workaround?

I'm using the gritter gem and followed the documentation pretty much to the tee.

the gem works with: <%= javascript_include_tag 'application' %>

but doesn't work with:
<%= javascript_importmap_tags %>

Is it possible to make an older gem work with importmap_tags by importing it differently?

vendredi 30 juin 2023

(Ruby on Rails validates_confirmation_of) How to switch error message to the confirmation field?

In Ruby on Rails 3.2, I am trying to validate password confirmation with this:

validates_confirmation_of :password

Rails will add the validation error to the :password field. How do I make the validation error be added to the :password_confirmation field instead?

samedi 24 juin 2023

AI websites explore now

I collected the best 26 AI websites that can help marketers, Developers, Editors, Designers

Artificial intelligence (AI) is a rapidly growing field that has been making waves in various industries. Notably, AI is being used to automate and optimize different processes, making them more efficient and accurate.

jeudi 22 juin 2023

I can't update it

The entry is not updated, it should change between true and false

class AsistenciaController < ApplicationController
  def asistencia
    @asistencia = User.all
  end

  def update
    @username = User.find(params[:username])
    @entry = User.find(params[:entry])
    if @asistencia.update(asistencia_params)
      redirect_to asistencia_path, notice: "Asistencia guardada correctamente"
    else 
      render :edit, status: :unprocessable_entity
    end
  end
end

Started POST "/guardar_asistencia" for 127.0.0.1 at 2023-06-22 10:56:34 -0500
Processing by AsistenciaController#update as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "user_username"=>"", "username"=>"1", "entry"=>"false", "commit"=>"Registrar"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/asistencia_controller.rb:7:in `update'
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", nil], ["LIMIT", 1]]
  ↳ app/controllers/asistencia_controller.rb:8:in `update'
Completed 404 Not Found in 19ms (ActiveRecord: 0.4ms | Allocations: 4468)



ActiveRecord::RecordNotFound (Couldn't find User with 'id'=false):

I tried with strong parameters and with patch but it doesn't work

I was hoping that by inserting the username I could change the entry between true and false

mercredi 21 juin 2023

How to render filter in index page in active admin

I filter the index page using the filter. Then I go to the view page and come back to the index page. How can I retain the currently applied filter until the clear filter is clicked?

Can someone please help with this? Thanks in advance.

samedi 17 juin 2023

Rails calculating a virtual column using 2 other virtual columns

I need help converting the following MySQL query into an ActiveRecord Query that will produce a relation with IP records as object. To explain this in a better way, How to convert the following query in How to sum two virtual column into third column in sql in ActiveRecord query ?

select a_id
u_c,
i_c,
(u_c + i_c) as t_c
from (
    select distinct a.id as a_id,
    (   SELECT count(b.id) FROM UP b
        WHERE b.i_p_id = a.id
        AND b.role = "L"
    ) as u_c,
    (   SELECT count(b.id) from UP b
        WHERE b.institution_package_id = a.id
        AND b.role = "I"
    ) as i_c
    from IP a
    left outer join UP b on b.IP = a.id       
) sub 

Let me explain a litte more. I have 2 tables where I am querying into the 1st table and calculating 3 virtual columns. The 3rd column will be the sum of the other 2 virtual columns. Thanks for the help.

jeudi 15 juin 2023

Gem devise_auth_token: How to utilize the remember_created_at field?

I'm using the gem devise_token_auth for authentication in my Ruby on Rails web application. I noticed that there is a remember_created_at field created as part of the gem's functionality. However, I'm unsure about the purpose or intended use of this remember_created_at field.

I tried making a login request with the following details:

POST http://localhost:3000/auth/sign_in
{
    "email": "....",
    "password": "...",
    "remember_me": true
}

But I observed that the remember_created_at field remains unset and has a value of null.

Could someone please clarify the purpose of the remember_created_at field in devise_token_auth and how it should be properly utilized? Am I missing any additional configurations or steps to ensure the value is set correctly when remember_me is set to true?

Thank you in advance for any insights or guidance.

mercredi 14 juin 2023

Updated heroku stack and now having will_paginate error

So I updated my heroku stack on my web app and am using ruby 3.2.2 with will_paginate 4.0, but am now receiving an error on one of my pagination pages. The specific error I'm getting is

2023-06-15T00:33:11.759517+00:00 app[web.1]: Rendered users/index.html.erb within layouts/application (Duration: 2.6ms | Allocations: 1025)
2023-06-15T00:33:11.759543+00:00 app[web.1]: Rendered layout layouts/application.html.erb (Duration: 2.7ms | Allocations: 1069)
2023-06-15T00:33:11.759701+00:00 app[web.1]: Completed 500 Internal Server Error in 7ms (ActiveRecord: 2.5ms | Allocations: 2352)
2023-06-15T00:33:11.760282+00:00 app[web.1]: 
2023-06-15T00:33:11.760282+00:00 app[web.1]: ActionView::Template::Error (wrong number of arguments (given 4, expected 3)):
2023-06-15T00:33:11.760282+00:00 app[web.1]: 13:   <h3><%= link_to "Create New Dude", new_user_path %></h3>
2023-06-15T00:33:11.760283+00:00 app[web.1]: 14: <% end %>
2023-06-15T00:33:11.760283+00:00 app[web.1]: 15:
2023-06-15T00:33:11.760284+00:00 app[web.1]: 16: <%= will_paginate %>
2023-06-15T00:33:11.760284+00:00 app[web.1]: 17:
2023-06-15T00:33:11.760284+00:00 app[web.1]: 18: <table>
2023-06-15T00:33:11.760284+00:00 app[web.1]: 19:   <thead>
2023-06-15T00:33:11.760284+00:00 app[web.1]: 
2023-06-15T00:33:11.760285+00:00 app[web.1]: app/views/users/index.html.erb:16

With the actual code being

<%= will_paginate %>

<table>
  <thead>
    <th></th> <!-- Icon -->
    ... a bunch of stuff you don't need to see ...
  </thead>
  <tbody>
    <%= render @users %>
  </tbody>
</table>

<%= will_paginate %>

I can't find any clear documentation on will_paginate 4.0 on why this would be throwing that specific error of wrong number of arguments (given 4, expected 3). The only thing I can find is the new basic will_paginate use here https://github.com/mislav/will_paginate. Do I need to somehow bundle my table that I used to paginate into a new structure?

Any help would be greatly appreciated.

lundi 12 juin 2023

Show image from controller in rails

I am displaying an image in view using <%= image_tag(@staff.attachment_url(@staff.image), alt: "No image", width: "100px", height: "100px") %> which is working fine.

Here attachment_url is method for creating dynamic url every time you open the image i.e. staff_profiles/images/b64f8b457dddf968712401bf07a8d08ba7f1ce3a326598ec2144f1c995309e06 and also this image is valid for 30 second only and after 30 second when you refresh or open the same url it will show Access denied.

Everything here is working fine.

Like this image i have other attachments to download/view with download link. when any user open page this attachment_url calls at the time of page load / show method but after 30 seconds this download link expires and when user click on the link it shows Access Denied. I want to call the attachment_url when user click on download link after 1 minute or 5 minutes or 10 minutes of page load.

So I need to open the image or create download link url from controller, Not like mentioned above and also want to use the method given above attachment_url which will help to create url dynamic.

Thanks

dimanche 11 juin 2023

FFMPEG gem is not generate correct bitrate value for a video in rails

I am using FFMPEG gem in rails, and I want to store bitrate value for a video in a table

I put this code in utility library/module

movie = FFMPEG::Movie.new(path)
media_detail = {duration: movie.duration, bitrate: movie.bitrate, resolution: movie.resolution}

On the show page I am using number_to_human_size rails helper method for more understandable representation

number_to_human_size(convert_kilobyte_to_byte(file.bitrate))

def convert_kilobyte_to_byte(bitrate_value)
     (bitrate_value.to_i*125)
end

FFMPEG gem generates everything as expected but in bitrate there is some problem and i really don't know why

mardi 6 juin 2023

I want to use a Datetime to save the entry and exit time, without the time being altered

Example of what I expect:

Time: 15:36 p.m.

Entrance = 12:30 pm

Exit = 15:36 p.m

Example of what I get:

Time: 15:36

Entry: 15:36

Exit: 15:36

Try with datetime.now, datetime.new

<%= fields = [:id, :email, :username, :entry, :entrada, :salida].join(";") %>
<% @users.each do |users| %>
<% id = users.id %>
<% email = users.email %>
<% username = users.username %>
<% entry = users.entry %>
<% entrada = Time.zone.now %>
<% salida = Time.zone.now %>
<%= [id.to_s, email, username, entry, entrada, salida].join(";") %> 
<% end %>    

How to debug rails application code in deployment environment

I am deploying a rails application on fly.io. The application is throwing an error on the web page but not getting details of the error on the flyctl logs (application logs). Please, how do I go about getting the error details on the application logs?

Thanks

"no implicit conversion of Array into String"

please I just developed a game in Ruby on Rails, and I am about to deploy it. Everything works fine in the development stage but keeps on getting "ActionView::Template::Error (no implicit conversion of Array into String):" in the deployment environment. The error pointed me to a particular line of code which is,

def passcode
  JSON.parse(game.passcode)
end

This is the output of my object before the JSON.parse;

"[\"ORANGE\", \"YELLOW\", \"PURPLE\", \"GREEN\"]"

The method above output;

["ORANGE", "YELLOW", "PURPLE", "GREEN"]

The passcode was used to get the game outcome after the player won or lost the game.

def game_outcome
 if !attempts.empty? && passcode == last_attempt
  return "Congratulations!"
 elsif attempts.size == guesses.size && passcode != last_attempt
  return "Sorry, you've lost! It was a bit difficult"
 end
end

I have tried to see the output of the method on my local machine and it outputs an array, which I think it's the right thing

I will appreciate your assistance.

Overriding module's private method which included to controller from external gem in Rails's Rspec test

I want to override private method as same as i wrote at title.

I have rspec controller test code, and i have to change some part of code.

I'm testing controller's method, and it is using external gem's private method.

  • Structure

External gem
┗ Module A
┗ Module B (inside Module A)
┗ private method Z
# def Z
      puts 1
      puts 2
      puts 3
end

Rails App
┗ Controller 1
┗ public action method login
┗ #login method calls A::B::Z


Rspec test
┗ Controller 1 (RSpec.describe Controller_1, type: :controller ...)
┗ test login (describe '#login' ..., context 'with wrong method..')

# I WANT TO CHANGE 'method Z' IN HERE LIKE
def Z
      puts 1
      puts 100
      puts 3
end


Can i do this in Rspec in Rails application?




if i use stub like this,

  before do
    allow(controller).to receive(:method_Z) #and contains puts 1, puts 100, puts3 ...
  end

  expect(response) #contains puts 1, puts 100, puts3 ...

i thought test would not be as i expected, so i'm wondering how to override method in rspec..

mercredi 31 mai 2023

submit button doesnot lead back to index in Ruby on Rails

I am new to Ruby on rails and i was trying to figure out where my code is failing. I created an Articles table so when i go to articles/new where if have the view to create article after i click on submit button it doesnot go to /articles but in terminal, it shows that a post request was made.

I have created a table articles and Model Article along with article_controller class also in the routes i have added resources :articles

But when i visit to articles/new and create a new article using the form i can see the create fn in the controller is called due to the POST request on article_path (/articles/) (because i tried to save the article into db and it did got saved) but when i try to display the article details using render plain: @articles.inspect nothing happens and it remains on /articles/new even after hitting the submit button (even if the create fn in empty it stays on that page). Please Help!

Controller

class ArticlesController < ApplicationController
    def show
        @article = Article.find(params[:id])
    end
    def index
        @articles = Article.all()
    end
    def new

    end
    def create
        render plain: @article.inspect
    end
end

Model

class Article < ApplicationRecord
    validates :title, presence: true, length: {minimum: 3, maximum: 50}
    validates :description, presence: true, length: {minimum: 10, maximum: 100}
end

New Form

<h1>Create an Article <h1>
<%= form_with scope: :article, url: articles_path, method: :post, local: true do |f| %>
    <p>
        <%= f.label :title %><br/>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.label :description %><br/>
        <%= f.text_area :description %>
    </p>
    <p>
        <%= f.submit %>
    </p>
<% end %>

Index Page

<h1>Showing All Articles</h1>

<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Description</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <% @articles.each do |article|%>
            <tr>
                <td><%= article.title%></td>
                <td><%= article.description%></td>
                <td>PlaceHolder</td>
            </tr>
        <% end %>
    </tbody>
</table>

samedi 27 mai 2023

How to preserve time data when page is refreshed in Ruby on Rails?

How can I get it to return the time without changing when I refresh the page (example: it's 12:02, I refresh the page at 12:05 and 12:02 is not saved, 12:05 appears)

 def change
    create_table :registers do |t|
      t.string :worker
      t.string :code
      t.time :work_hour
      
      t.timestamps
    end
    add_index :registers, :worker
  end

I was hoping that the time would not be edited when refreshing the page

jeudi 25 mai 2023

Ruby Rails program to search a value in all fields of all collections from all the mongodb databases of your app

This rather my solution which i wanted to share, as i didn't any such solutions that are straight forward. This solution needs to be provided with all the database URI configured in your mongoid.yml.

uriList=['mongodb://127.0.0.1:27017/my_app_db1',
    'mongodb://127.0.0.1:27017/my_app_db2', 
    'mongodb://127.0.0.1:27017/my_app_db3', 
    'mongodb://127.0.0.1:27017/my_app_db4'
     ]

def searchDb(dbUri, search_value)
    puts "Searching in #{dbUri}++++++++++++++++++++++++++++++++++++++++++"
    client = Mongo::Client.new(dbUri)
    # List all collections in the current database
    #collections = client.database.list_collections.map(&:name)
    collections = client.database.list_collections
    # search the collection
    collections.each do |collection|
            flag=false
            begin
                puts "      searching in collection- #{collection[:name]}"
                colln=client[ collection[:name] ]
                # Iterate over the fields of each collection
            colln.find.each do |document|
                document.each do |field, value|
                        # Perform a case-insensitive search for the value
                        if value.to_s.downcase.include?(search_value.downcase)
                            flag=true
                            puts "          Collection: #{collection[:name]}"
                            puts "          Field: #{field}"
                            puts "          Value: #{value}"
                            puts "\n"
                        end
                    end
                end
        rescue
            puts "      ** failed to search in #{collection[:name]} ** "
            puts "" 
        end
        unless flag
            puts "          --not found or failed in #{collection[:name]} ** "
        end
    end
    
end

#call function 
uriList.each do |myUri|
    searchDb(myUri, 'searchValue')
end

i tried with bits pieces of code.

mardi 23 mai 2023

What could be causing my Ruby application to only download a 1 KB file when trying to get a video from a private S3 bucket?

We have an S3 private bucket, and the objects within it are also private. We only upload PDF and MP4 files.

I am able to download the PDF files from a Ruby application. However, when I try to download a video file, I only receive a 1 KB file. Can someone please help me identify what might be missing here?

I attempted to make the object public in the S3 bucket and then tried to download the video.

It successfully downloaded with the expected file size.

mardi 9 mai 2023

ruby combine hash related key

I want to combine related key for example:

my_hash = {key_a: "value a", key_b: "value b", key_c: "value c"}

I want the result to be:

{ key:
  [
    { a: "value a" },
    { b: "value b" },
    { c: "value c" }
  ]
}

It can be easily do that by getting each key explicitly but the problem is, it can define dynamic key.

THE PROBLEM is key_ is can be any, you can't determine what is after key_. It can be key_r, key_w, key_z

samedi 6 mai 2023

Postal mail server codebase; "logged_in?" method not defined in ApplicationController

I just got to know of postal a few days ago and I'm very excited about all the features it offers out of the box for free. But as a junior rails dev, I'm tempted to play around with it to see if I can add my own features. I've managed to set it up and get it working. But I have a problem. I don't seem to understand what is going on in the application controller completely. There's one method "logged_in?" which get's used a lot. But it's not defined anywhere in the codebase. And I don't seem to find any gem which provides this method for me to guess it being automatically loaded in to the code, as rails does with some other modules. Below is the code:

require "authie/session"

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  before_action :login_required
  before_action :set_timezone

  rescue_from Authie::Session::InactiveSession, with: :auth_session_error
  rescue_from Authie::Session::ExpiredSession, with: :auth_session_error
  rescue_from Authie::Session::BrowserMismatch, with: :auth_session_error

  private

  def login_required
    return if logged_in?

    redirect_to login_path(return_to: request.fullpath)
  end

  def admin_required
    if logged_in?
      unless current_user.admin?
        render plain: "Not permitted"
      end
    else
      redirect_to login_path(return_to: request.fullpath)
    end
  end

  def require_organization_owner
    return if organization.owner == current_user

    redirect_to organization_root_path(organization), alert: "This page can only be accessed by the organization's owner (#{organization.owner.name})"
  end

  def auth_session_error(exception)
    Rails.logger.info "AuthSessionError: #{exception.class}: #{exception.message}"
    redirect_to login_path(return_to: request.fullpath)
  end

  def page_title
    @page_title ||= ["Postal"]
  end
  helper_method :page_title

  def redirect_to_with_return_to(url, *args)
    if params[:return_to].blank? || !params[:return_to].starts_with?("/")
      redirect_to url_with_return_to(url), *args
    else
      redirect_to url_with_return_to(url), *args
    end
  end

  def set_timezone
    Time.zone = logged_in? ? current_user.time_zone : "UTC"
  end

  def append_info_to_payload(payload)
    super
    payload[:ip] = request.ip
    payload[:user] = logged_in? ? current_user.id : nil
  end

  def url_with_return_to(url)
    if params[:return_to].blank? || !params[:return_to].starts_with?("/")
      url_for(url)
    else
      params[:return_to]
    end
  end

  def redirect_to_with_json(url, flash_messages = {})
    if url.is_a?(Array) && url[0] == :return_to
      url = url_with_return_to(url[1])
    else
      url = url_for(url)
    end

    flash_messages.each do |key, value|
      flash[key] = value
    end
    respond_to do |wants|
      wants.html { redirect_to url }
      wants.json { render json: { redirect_to: url } }
    end
  end

  def render_form_errors(action_name, object)
    respond_to do |wants|
      wants.html { render action_name }
      wants.json { render json: { form_errors: object.errors.full_messages }, status: :unprocessable_entity }
    end
  end

  def flash_now(type, message, options = {})
    respond_to do |wants|
      wants.html do
        flash.now[type] = message
        if options[:render_action]
          render options[:render_action]
        end
      end
      wants.json { render json: { flash: { type => message } } }
    end
  end

  def login(user)
    if logged_in?
      auth_session.invalidate!
      reset_session
    end
    Authie::Session.start(self, user: user)
    @current_user = user
  end

end

vendredi 5 mai 2023

How to use Joins followed by left outer join in ruby on rails?

I have the following database schema structure:

School
has_many :students

Students
has_many :books

Books
(has an attribute pages(integer))

The issue is I want a total of all the pages of a book a student has at the school level. But there is also a possibility that a student might not have any book.

I want to select the following rails query using ruby code and methods like joins and includes:

SELECT * FROM school INNER JOIN students ON students.school_id = schools.id LEFT OUTER JOIN books ON books.student_id = students.id

I have tried the following:

School.joins({:students => :books}).all

But this will not take into account those students who do not have any books. How to solve this?

lundi 1 mai 2023

Rails 3.2 -> 4.2 Emergency upgrade, memory leak on Heroku

with the May 1st deprecation of the Heroku-18 stack, I needed to update a very old Rails app to the minumum version required. It was though, but I got it working.

I have a completely new version to deploy soon based rails 6, but for the time being, I need to run this old app. I noticed the memory footprint almost doubled (on 3.2 it was avg 90-120% of 512mb ram) and my immediate stop gap solution is to update the dynos to 2x 1gb ram, however, I would like to pinpoint the isse.

2023-05-01T17:46:12.209506+00:00 heroku[web.1]: Process running mem=990M(188.0%)
2023-05-01T17:46:12.211046+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2023-05-01T17:46:33.107262+00:00 heroku[web.1]: Process running mem=990M(188.0%)
2023-05-01T17:46:33.111875+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2023-05-01T17:46:54.224029+00:00 heroku[web.1]: Process running mem=990M(188.0%)
2023-05-01T17:46:54.227886+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2023-05-01T17:47:15.327098+00:00 heroku[web.1]: Process running mem=990M(188.0%)
2023-05-01T17:47:15.328612+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2023-05-01T17:47:36.150757+00:00 heroku[web.1]: Process running mem=990M(188.0%)
2023-05-01T17:47:36.152131+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2023-05-01T17:47:57.287322+00:00 heroku[web.1]: Process running mem=990M(188.0%)
2023-05-01T17:47:57.289241+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)

The old app used memcachd, the new app is using in-memory caching, which can surely be one of the issues. Can I switch to file-base caching? Should I look into Redis caching or any other solution that I have not considered?

This app is also using Unicorn, all my newer apps are using Puma. Is this worth looking into?

vendredi 28 avril 2023

How to validate an updated has-many-through collection

I am try to figure out how to properly validate a model collection whenever that collection is updated using the << collection operator. In our legacy app (Rails 3.2.1), I found that platform_collection_obj.platforms is updated using << operator

Example:

collection.platforms << new_platform

In researching how to validate that each platform in platforms collection has appropriate data, I found that I should use custom-validation function. So I tried adding each_platform_branch_id validation function to PlatformCollections Model. However, I found in testing (via rails console) that the validation was not triggered.

In reading Has-Many-Association-Collection Info, I came across this

Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record. This will also run validations and callbacks of associated object(s).

This excerpt indicates that using << to perform update on collection.platforms will not trigger the parent validations, which in this case would be the PlatformCollection:each_platform_branch_id validation function. I know that manually perforning collection.save would trigger validation, but it would be too late b/c << has already updated the DB.

So to restate the question is: How do I properly validate a has-many-through-model collection whenever that collection is updated using the << collection operator?

PlatformCollections Model

class PlatformCollection < ActiveRecord::Base
  belongs_to :tezt
  has_many :platform_collection_platforms, :order => "platform_collection_platforms.default DESC"
  has_many :platforms, :through => :platform_collection_platforms, :order => "platform_collection_platforms.default DESC"

  def each_platform_branch_id
    platforms.each do |p|
      if p.branch_id != @branch.id
        err_msg = "Invalid Platform: #{p.to_json} for PlatformCollection: #{self.to_json}. " \
                  "Expected Branch: #{@branch.id}, Actual Branch: #{p.branch_id}"
        errors.add(:platform, err_msg)
      end
    end
  end

Platforms Model

class Platform < ActiveRecord::Base
  attr_accessible :name
  belongs_to :branch
  has_many :platform_collection_platforms
  has_many :platform_collections, :through => :platform_collection_platforms

Can't set changePasswordAtNextLogin to true - Google Admin Directory V1 API Rails

I am using the google-apis-admin_directory_v1 gem for Rails. According to the documentation, if you set the field changePasswordAtNextLogin to true in the insert user method it Indicates if the user is forced to change their password at next login however, when I have created users via the API with this attribute set to true it has not asked me to change my password. Here is my method call:

google_name =
      Google::Apis::AdminDirectoryV1::UserName.new(
        given_name: 'John',
        family_name: 'Smith',
        full_name: 'John Smith'
      )
    google_user =
      Google::Apis::AdminDirectoryV1::User.new(
        password: 'password',
        primary_email: 'john.smith@example.com',
        name: google_name,
        change_password_at_next_login: true
      )

jeudi 27 avril 2023

Respond_to format in Rails 5

I am having problems getting respond_to format working in Rails 5 app in controller, is just for downloading a csv list of users, as below: def customers_graylist_export @graylisted_users = Customer.where(status_trust: 'graylist') respond_to do |format| format.csv do response.headers['Content-Type'] = 'text/csv' response.headers['Content-Disposition'] = "attachment; filename=ListaCinza.csv" end end end

And getting unknown format error on line "respond_to do |format|" the mime type is registered in mime_types initializer, and this should be straightforward, but Rails 5 is a little quirky!

Any suggestions welcome?

Many Thanks

mardi 25 avril 2023

HTTPS request for ruby

I would like to take information from another website. Therefore (maybe) I should make a request to that website (in my case a HTTP GET request) and receive the response.

How can I make this in Ruby on Rails?

If it is possible, is it a correct approach to use in my controllers?

if another website is http://www.test.com, it OK but https://www.test.com,

i got it SyntaxError ((eval):1: syntax error, unexpected '<'

^ (eval):2: syntax error, unexpected tCONSTANT, expecting end-of-input 404 Not Found ^~~): app/models/cart_payment.rb:155:in `eval'

SyntaxError ((eval):1: syntax error, unexpected '<'

^ (eval):2: syntax error, unexpected tCONSTANT, expecting end-of-input 404 Not Found ^~~): app/models/cart_payment.rb:155:in `eval'

url = URI.parse("https://test.com")

  http = Net::HTTP.new(url.host, url.port);
  request = Net::HTTP::Post.new(url)
  request["Content-Type"] = "application/json"

  request.body = JSON.dump(body)

  response = http.request(request)

  response_body = eval(response.read_body)

  message = response_body[:Response]

Not able to install ruby 2.3.1 in ubuntu 22.01 using rbenv

Not able to install ruby 2.3.1 in ubuntu 22.01 using rbenv it is giving the fllowing error response:

vidur@Vidur-PC:~/rails_apps/Connectivity-Web$ rbenv install 2.3.0
To follow progress, use 'tail -f /tmp/ruby-build.20230425154726.452387.log' or pass --verbose
Downloading openssl-1.0.2u.tar.gz...
-> https://dqw8nmjcqpjn7.cloudfront.net/ecd0c6ffb493dd06707d38b14bb4d8c2288bb7033735606569d8f90f89669d16
Installing openssl-1.0.2u...
Installed openssl-1.0.2u to /home/vidur/.rbenv/versions/2.3.0

Downloading ruby-2.3.0.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.bz2
Installing ruby-2.3.0...

WARNING: ruby-2.3.0 is past its end of life and is now unsupported.
It no longer receives bug fixes or critical security updates.


BUILD FAILED (Ubuntu 22.10 using ruby-build 20230424)

Inspect or clean up the working tree at /tmp/ruby-build.20230425154726.452387.KXKRoa
Results logged to /tmp/ruby-build.20230425154726.452387.log

Last 10 log lines:
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/store.rb:749:in `save'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/generator/ri.rb:27:in `generate'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:535:in `block in generate'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:530:in `chdir'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:530:in `generate'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:513:in `document'
    ./bin/rdoc:20:in `<main>'


make: *** [uncommon.mk:442: rdoc] Error 1

please suggest the possible solution thanks in advance.