mardi 29 novembre 2022

Can't make code_ownership and code_teams gems to work

The gems code_teams, code_ownership should allow one to tag files/whole folders by team name but after adding them to my project, running bundle install etc, I still encounter the same error

Passed `nil` into T.must

sample team file (placed in config/teams as advised) is as following

name: Smurfs
owned_globs:
  - folder/filename1.rb

The code where I try to use the info is :

x = CodeOwnership.for_backtrace(e.backtrace)

dimanche 20 novembre 2022

Rails call custom validation before .new or .create

I make objects in controller's loop.

I need to check pet_name array before loop starts. (because i got undefined method 'each' for nil:NilClass when params[:pet_name].each do |pid|) runs)

But my validation always called after User.new or User.create. I want to change to validate as when i push submit button and check validation, and redirects back when pet_name array is nil. Ho can i change my code?

Controller

  def create
    user_name = params[:user_name]
    
    params[:pet_name].each do |pid|
      @user = User.new
      @user.name = user_name
      @user.pet_name = pid
      render :new unless @user.save
    end
    redirect_to users_path
  end

User.rb

class User < ApplicationRecord
  has_many :pet

  validates :name, presence: true
  validates :pet_name, presence: true
  validate :check_pet
  def check_pet
    if pet_name.nil?
      errors.add(:pet_name, 'at least one pet id')
    end
  end
end

Prams structure

  { name: 'blabla', pet_name: ['blabla', 'blablabla', 'bla'] }

samedi 19 novembre 2022

Obstacle with Ruby Rails Authentication

I am a brand new Ruby on Rails User

When I enter localhost:3000 ,

I get an error reading

Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development You have 2 pending migrations: 20221119205559_add_devise_to_users.rb 20221119211811_drop_users_table.rb

# Raises <tt>ActiveRecord::PendingMigrationError</tt> error if any migrations are pending.
      def check_pending!(connection = Base.connection)
        raise ActiveRecord::PendingMigrationError if connection.migration_context.needs_migration?
      end

      def load_schema_if_pending!

In a nutshell, it was working before but I attempted to create a a basic authentication page(which was also working) , but for some reason when I clicked sign up I received an error also.

Thank you for any tips on how to fix this!

I have tried to

rake db:drop
rake db:create
rake db:migrate

Editing the migrate file with: 

 edit your migration file

class DropUsersTable < ActiveRecord::Migration
  def change
    drop_table :users
  end
end

Then doing rake db:migrate

Also, I have run :


rails generate devise:install rails generate devise User bundle exec rake db:migrate



jeudi 17 novembre 2022

Creating array value in Rspec with let() method

how can i make array value in rspec test?

If I make array like this (in SAMPLE_spec.rb file), ->>

let(:fruit) { [name:  ‘apple’, color: ‘red’] }

fruit.length --->> this becomes error

fruit[0].length --->>this works well

i want to make array and use like fruit.length. how can i change my code?

mercredi 16 novembre 2022

Write a program which gets a number from a user and identify whether it is an Integer or a Float in ruby

I am trying this :

print " Enter Value " num = gets.chomp

also tried .kind_of? but didn't work

if num.is_a? Float
print " Number is in float "

also tried .kind_of? but didn't work

else num.is_a? Integer
print " Number is in integer "

end

dimanche 13 novembre 2022

Cannot Send Email From Send Grid With Attachment 300 kb

I try to send email using sendgrid with attachment file (pdf). Its working good for attachment less than 250 kb. But when I try to send email with attachment file with size above 250 kb, I get error from send grid said, 552 5.2.3 your message exceeded google's size limit, but the attachment file only 300 kb. Can someone help me with this issue? thank you in advance.

jeudi 10 novembre 2022

2 arrays insert via (column) double dimension array ruby (short method)

From this initialize array:

x = []
y = [1,2,3,4,5]
z = ["a", "b", "c", "d", "e"]

I want x result to be like this:

=> [[1,"a"], [2,"b"], [3,"c"], [4,"d"], [5,"e"]]

Is there any short method to do this without using nested loop?

Can we call ASP.Net page load function from Rails application?

I'm facing an issue while calling the ASP.Net function from Rails. First I want to know that Is it possible to call the ASP.Net function from Rails?

I tried to call it but facing <Net::HTTPUnauthorized 401 Unauthorized readbody=true> error message

I also passed the username and password with it.

Thank you.

lundi 7 novembre 2022

OPTIMIZE QUERY ON RAILS - POSTGRESQL

I have 3 scopes: 1 - lists the promotions in progress. 2 - sort out of stock last 3 - list the promotions that are not in progress.

Is it possible to combine everything in a single scope? It would be: List the promotions in progress, in order of stock from highest to lowest, and then the promotions that are not in progress.

I tried, but I couldn't.

scope :in_progress, -> { start_and_end_dates.in_weeks.between_hours }
    
scope :without_stock_last, lambda {
  select('promotions.*, (CASE WHEN offers.current_inventory > 0 THEN 1 ELSE 0 END) AS "is_available"')
   .order('is_available DESC')
   .group('promotions.id, offers.current_inventory, offers.created_at')
}
    
scope :not_progress, lambda {
  promotions_in_progress = Promotion.in_progress.pluck(:id).join(",")
  Promotion.with_estabilishment.select("promotions.*, (CASE WHEN promotions.id NOT IN (#{promotions_in_progress}) THEN 0 END) AS is_unavailable")
  .order('is_unavailable DESC')
}

mercredi 2 novembre 2022

Unpermitted parameter: :image. (carrierwave )

i am creating a form where you can upload the image file, but whenever i submit the form, it dosent permit the image and in the terminal it shows "Unpermitted parameter: :image. Context: { controller: InstrumentsController, action: update, request: #ActionDispatch::Request:0x00007f1955b24b50, params: {"_me................."

also if i check using the rails console if the image is being uploaded or not by typing the Instrument.all (Instrument is a table in database), it shows that it is nil,

i have permitted the :image in params

instruments_controller.rb

class InstrumentsController < ApplicationController
  before_action :set_instrument, only: %i[ show edit update destroy ]
  before_action :authenticate_user!, except: [:index, :show]

  # GET /instruments or /instruments.json
  def index
    @instruments = Instrument.all.order("created_at desc")
  end

  # GET /instruments/1 or /instruments/1.json
  def show
  end

  # GET /instruments/new
  def new
    @instrument = current_user.instruments.build
  end

  # GET /instruments/1/edit
  def edit
  end

  # POST /instruments or /instruments.json
  def create
    @instrument = current_user.instruments.build(instrument_params)

    respond_to do |format|
      if @instrument.save
        format.html { redirect_to instrument_url(@instrument), notice: "Instrument was successfully created." }
        format.json { render :show, status: :created, location: @instrument }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @instrument.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /instruments/1 or /instruments/1.json
  def update
    respond_to do |format|
      if @instrument.update(instrument_params)
        format.html { redirect_to instrument_url(@instrument), notice: "Instrument was successfully updated." }
        format.json { render :show, status: :ok, location: @instrument }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @instrument.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /instruments/1 or /instruments/1.json
  def destroy
    @instrument.destroy

    respond_to do |format|
      format.html { redirect_to instruments_url, notice: "Instrument was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_instrument
      @instrument = Instrument.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def instrument_params
      params.require(:instrument).permit(:brand, :model, :description, :condition, :finish, :tiitle, :price, :image)
    end
end

and inside the model (ignore 'tiitle' as i have already done a typo and continue to use it instead of 'title')

instrument.rb

class Instrument < ApplicationRecord
    
    mount_uploader :image, ImageUploader

    belongs_to :user, optional: true
    

    validates :tiitle, :brand, :price, :model, presence: true
    validates :description, length: { maximum: 1000, too_long: "%{count} is the maximum allowed characters" }
    validates :tiitle, length: { maximum: 140, too_long: "%{count} is the maximum allowed characters" } 
    validates :price, numericality: { only_integer: true }, length: { maximum: 7 } 

    BRAND = %w{ Fender Gibson Epiphone ESP Martin Dean Taylor Jackson PRS Ibanez Charvel Washburn }
    FINISH = %w{ Black White Navy Blue Red Clear Satin Yellow Seafoam }
    CONDITION = %w{ New Excellent Mint Used Fair Poor }



end

_form.html.erb

<%= simple_form_for @instrument, html: { multipart: true } do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

  <div class="form-inputs">
  <div class="row ">
    <div class="col mx-auto">
      <div class="card mt-2 mx-auto p-4 bg-light">
        <div class="card-body bg-light">

        <div class = "container">
                          
        <div class="controls">
      
          <div class="row">
            <div class="col-md-10">
              <div class="form-group">
              <%= f.input :tiitle, input_html: {class: "form-control"} %>
              </div>
            </div>

            
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <%= f.input :model, input_html: {class: "form-control"} %>
              </div>
            </div>

            <div class="col-sm-2">
              <div class="form-group">
                <%= f.input :price %>
              </div>
            </div>
          </div> 

        </div>
        </div>

    <%= f.input :description %>

    <%= f.label :condition %>
    <div class="row">
      <div class="col-sm-1">
        <div class="form-group">
            
            <%= f.input_field :condition, collection: Instrument::CONDITION, prompt: "Select Condition" %>
        </div>
      </div>
    </div>


    <%= f.label :brand %>
    <div class="row">
      <div class="col-sm-1">
        <div class="form-group">
          <%= f.input_field :brand, collection: Instrument::BRAND, prompt: "Select Brand" %>
        </div>
      </div>
    </div>


    <%= f.label :finish %>
    <div class="row">
      <div class="col-sm-1">
        <div class="form-group">
          <%= f.input_field :finish, collection: Instrument::FINISH, prompt: "Select Finish" %>   
        </div>
      </div>
    </div>



    <%= f.input :image, as: :file, input_html:{ multiple: true, class:"file-input instrument-image" }, label: false, wrapper: false %>
  </div>  
    </div>
      </div>
        </div>
          </div>


  <div class="form-actions">
    <div class="row">

      <div class="col-sm-1">
        <%= f.button :submit, "Create instrument", class: "btn btn-success create-instrument-btn" %>
      </div>
    

      <div class="col-sm-2">
        <%= link_to "Cancel", instruments_path, class: "btn btn-danger cancel-instrument-btn" %>
      </div>

    </div>
  </div>



<% end %>

image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  version :thumb do
    process resize_to_fit: [400, 300]
  end

  version :default do
    process resize_to_fit: [800, 600]
  end

  # Add an allowlist of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_allowlist
    %w(jpg jpeg gif png)
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end
end

i am a newbie, according to the knowledge what i have understood is that we have to use html: {multipart: true} in the form initializing so that it accepts the uploader as file and permit the ':image' in controller's file and it should work but when i click the "Create" button, it dosen't upload the image and shows unpermitted params in terminal while i submit it and creates a new instrument with all fields except the uploader. Any fixes? :')