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?