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?