samedi 30 novembre 2019

undefined local variable or method `article_params' for

articles_controller.rb

''' class ArticlesController < ApplicationController def index @articles = Article.all end

def show
  @article = Article.find(params[:id])
end

def new
end

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render new
end

private
  def article_params
    params.require(:article).permit(:title, :text)
  end
end

end

'''

routes.rb

'''

Rails.application.routes.draw do
  #layout=false 
  get 'welcome/index'
  get 'welcome/second'
  get 'articles/new'
  post 'articles/new'
  #get 'articles/show'
  #get 'articles/index'
  #get 'articles/new'
  resources :articles
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root 'welcome#index'
end'

'''

show.html.erb

'''

Rails.application.routes.draw do
  #layout=false 
  get 'welcome/index'
  get 'welcome/second'
  get 'articles/new'
  post 'articles/new'
  #get 'articles/show'
  #get 'articles/index'
  #get 'articles/new'
  resources :articles
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root 'welcome#index'
end

'''

index.html.erb '''

<h1>Listing articles</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
    <th></th>
  </tr>

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
    </tr>
  <% end %>
</table>

'''

new.html.erb

'''

<%= form_for :article, url: articles_path do |form| %>
 <h1>new artical page</h1>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

'''

schema.rb

'''

ActiveRecord::Schema.define(version: 2019_11_30_073138) do

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "text"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

'''

database.yml

'''

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

'''

yymmddttss_create_articles.rb

'''

 class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :text

      t.timestamps
    end
  end
end

'''

i don't know where im making mistake. please when you reply it then make changes in above codes.

mercredi 27 novembre 2019

Write a complex Mongo query in Rails ORM

I want to convert mongo query to rails ORM query for the below json.

Rails query is:

db.collection.aggregate([
  {
    $match: {
      "data.toc.ge.ge._id": "5b"
    }
  },
  {
    $unwind: "$data.toc.ge"
  },
  {
    $unwind: "$data.toc.ge.ge"
  },
  {
    $group: {
      _id: null,
      book: {
        $push: "$data.toc.ge.ge._value"
      }
    }
  },
  {
    $project: {
      _id: 0,
      first: {
        $arrayElemAt: [
          "$book",
          0
        ]
      },

    }
  }
])

Please look at this as well:

https://mongoplayground.net/p/fb9IMkC1fCs

Collection is the corresponding class and this is what I've tried so far,

unwind2=  {'$unwind': "$data.toc.ge.ge"}
unwind3=  {'$unwind': "$data.toc.ge.ge.ge"}
group= {'$group': {_id: nil, book: {'$push': "$data.toc.ge.ge.ge._display_name"}}}
match= {'$match': {"data.toc.ge.ge.ge._id": "m121099"}}
project= {'$project': {_id: 0, 'mytopic': {'$arrayElemAt': ["$book",0]},}}

answer = collection.aggregate([match,unwind1,unwind2,unwind3,group,project]).to_a

mardi 26 novembre 2019

Form field doesn't get updated with AJAX

I'm trying to update the available rooms in a form, by making a POST request to my controller when arrival and departure dates are filled in the same form.

Unfortunately my inserted HTML doesn't seem to render, but I don't see where the bug is.

Code

reservations/new.html.erb

<%= simple_form_for [@hotel, @reservation] do |f|%>
  <div class="col col-sm-3">
    <%= f.input :arrival,
    as: :string,
    label:false,
    placeholder: "From",
    wrapper_html: { class: "inline_field_wrapper" },
    input_html:{ id: "start_date"} %>
  </div>
  <div class="col col-sm-3">
    <%= f.input :departure,
    as: :string,
    label:false,
    placeholder: "From",
    wrapper_html: { class: "inline_field_wrapper" },
    input_html:{ id: "end_date"} %>
  </div>

  <div class="col col-sm-4">
    <%= f.input :room_id, collection: @rooms, as: :grouped_select, group_by: proc { |room| room.room_category.name },  label:false %>
    <%#= f.input :room_id, collection: @room_categories.order(:name), as: :grouped_select, group_method: :rooms,  label:false %>
  </div>

  <%= f.button :submit, "Search", class: "create-reservation-btn"%>
<% end %>

script for reservations/new.html.erb

<script>
const checkIn = document.querySelector('#start_date');
const checkOut = document.querySelector('#end_date');
const checkInAndOut = [checkIn, checkOut];

checkInAndOut.forEach((item) => {
  item.addEventListener('change', (event) => {
    checkAvailability();
  })
})

  function checkAvailability(){

    $.ajax({
      url: "<%= rooms_availability_hotel_path(@hotel) %>" ,
      dataType: 'json',
      type: "POST",
      data: `arrival=${start_date.value}&departure=${end_date.value}`,
      success: function(data) {
        console.log('succes')
        console.log(data);
      },
      error: function(response) {
        console.log('failure')
        console.log(response);
      }
    });
  };
</script>

hotels_controller

def rooms_availability
  hotel = Hotel.includes(:rooms).find(params[:id])
  arrival = Date.parse room_params[:arrival]
  departure = Date.parse room_params[:departure]
  time_span = arrival..departure
  @unavailable_rooms = Room.joins(:reservations).where(reservations: {hotel: hotel}).where("reservations.arrival <= ? AND ? >= reservations.departure", arrival, departure).distinct
  @hotel_cats = hotel.room_categories
  @hotel_rooms = Room.where(room_category: hotel_cats)
  @rooms = hotel_rooms - @unavailable_rooms
  respond_to do |format|
    format.js
  end
end

def room_params
  params.permit(:arrival, :departure, :format, :id)
end

hotels/rooms_availability.js.erb

var selectList = document.getElementById('reservation_room_id')

function empty() {
  selectList.innerHTML = "";
}

empty();


    <% unless @rooms.empty? %>
      <% @hotel_cats.each do |cat|%>
        selectList.insertAdjacentHTML('beforeend', '<optgroup label=<%= cat.name %>>');
        <% cat.rooms.each do |room|%>
          <% if @rooms.include? room %>
            selectList.insertAdjacentHTML('beforeend', '<option value="<%= room.id %>"><%= room.name %></option>');
          <% end %>
        <% end %>
        selectList.insertAdjacentHTML('beforeend', '<optgroup>');
      <% end %>
    <% end %>

Print screen of form html

<div class="form-group grouped_select optional reservation_room_id">
  <select class="grouped_select optional" name="reservation[room_id]" id="reservation_room_id">
      <option value=""></option>
    <optgroup label="room category 1">
        <option value="6">1</option>
        <option value="7">2</option>
        <option value="8">3</option>
    </optgroup>
    <optgroup label="room category 2">
        <option value="16">1</option>
    </optgroup>
  </select>
</div>

logs

Processing by HotelsController#rooms_availability as JS
  Parameters: {"arrival"=>"2019-11-26", "departure"=>"2019-11-27", "id"=>"22"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ /Users/username/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  Hotel Load (0.3ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ↳ app/controllers/hotels_controller.rb:125
  CACHE Hotel Load (0.0ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ↳ app/controllers/hotels_controller.rb:103
  RoomCategory Load (0.3ms)  SELECT "room_categories".* FROM "room_categories" WHERE "room_categories"."hotel_id" = $1  [["hotel_id", 22]]
  ↳ app/controllers/hotels_controller.rb:103
  Room Load (0.3ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."room_category_id" IN ($1, $2)  [["room_category_id", 4], ["room_category_id", 9]]
  ↳ app/controllers/hotels_controller.rb:103
  Room Load (0.4ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."room_category_id" IN (SELECT "room_categories"."id" FROM "room_categories" WHERE "room_categories"."hotel_id" = $1)  [["hotel_id", 22]]
  ↳ app/controllers/hotels_controller.rb:115
  Room Load (1.7ms)  SELECT DISTINCT "rooms".* FROM "rooms" INNER JOIN "reservations" ON "reservations"."room_id" = "rooms"."id" WHERE "reservations"."hotel_id" = $1 AND (reservations.arrival <= '2019-11-26' AND '2019-11-27' >= reservations.departure)  [["hotel_id", 22]]
  ↳ app/controllers/hotels_controller.rb:115
  Rendering hotels/rooms_availability.js.erb
  Rendered hotels/rooms_availability.js.erb (0.6ms)
Completed 200 OK in 53ms (Views: 19.3ms | ActiveRecord: 3.3ms)

ActiveRecord Associations(has_one) - Access parent object

class Parent < ApplicationRecord
  has_one: child
end


class Child < ApplicationRecord
  belongs_to :parent
end


childrens = Child.includes(:parent)

puts childrens.to_json
[{"id":1,"parent_id":1,"name":"Jack"},{"id":2,"parent_id":2,"name":"Oleg"}]

In this case, we can access parent object like this: child.parent

But it is not possible to access parent object in view. Is there any way to include parent objects in each child?

Thank you!

Rails Application keep heating pg_type and pg_attribute table how to reduse this call

I am using ruby ruby-2.1.2, Rails 4.1.3 with Postgres and we see application keep heating pg_type and pg_attribute table.

How to validate and see who calling this query?

Query 1 : SELECT oid, typname, typelem, typdelim, typinput FROM pg_type
Query 2 :  SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                FROM pg_attribute a LEFT JOIN pg_attrdef d
                  ON a.attrelid = d.adrelid AND a.attnum = d.adnum
               WHERE a.attrelid = ?::regclass
                 AND a.attnum > ? AND NOT a.attisdropped
               ORDER BY a.attnum

dimanche 24 novembre 2019

Array returns first element blank in my Rails(3.2.11) multi-select

When I selected multiple values from select list then array returns the first value empty.

= f.select :assignedto, options_from_collection_for_select(User.all, 'name', 'name',f.object.assignedto),{}, { :multiple => true}

I tried with {:include_blank => false} and {:include_hidden => false} but this is not working for rails 3.2.11. I have many solutions to handle this empty value in the controller but I want to stop adding empty value in the array.

vendredi 22 novembre 2019

mardi 19 novembre 2019

one-liner for exit with message in capistrano

It is possible to have a one liner condition for exit with message?

if condition
  info "some message"
  exit
end

Can't start rails server after aws-sdk-3 installed

I know that there is a lot of such kind of questions, but still, I believe my case is slightly different. I recently decided to build in an AWS-S3 gem to my rails version 3 project. After the successfully aws-sdk gem have been installed, I've got an error message on rails server

/root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse/client/net_http/patches.rb:26:in `alias_method': undefined method `new_transport_request' for class `Net::HTTP' (NameError)
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse/client/net_http/patches.rb:26:in `apply!'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse/client/net_http/connection_pool.rb:10:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse.rb:34:in `require_relative'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse.rb:34:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:597:in `new_constants_in'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/aws-sdk-core.rb:2:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:597:in `new_constants_in'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-resources-3.59.0/lib/aws-sdk-resources.rb:1:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:597:in `new_constants_in'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-3.0.1/lib/aws-sdk.rb:1:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `each'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `each'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler.rb:120:in `require'
from /jasa/api/trunk/config/application.rb:7:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:28:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:28:in `block in <top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:27:in `tap'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:27:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

I've tried both

gem 'aws-sdk', '~> 3'

and

gem 'aws-sdk-s3', '~> 1'

Thanks a lot. Any help will be appreciated.

lundi 18 novembre 2019

Write a function that returns the position or positions of the lowest valued integer and can handle this array or any array

figures = [-1, -7, 1, 5, -7, 0];

You are not allowed to use .map , each, max or other similar ruby methods. I got this question in a coding challenge and I was unable to produce a good answer.

def getArrayIndex(number, i) 
  n=1 
  if number[i] < number[i+=n] 
    puts number[i] 
  else 
    puts number[i+=n] 
  end 
end 
p getArrayIndex(figures, 0) 

Is it possible to create a single executable file of a Ruby on Rails project?

How to create a single executable file for any rails project. How to create a single executable file for any rails project.

samedi 16 novembre 2019

Devise Sign in and sign up form not working correctly

I've been trying to build a simple login and sign up screen but the user data isn't saving when i hit submit button. This is the page in devise At first eveything was going well and i got rib of most of the errors on my own but ive been stuck with this for a week.

When i fill out the form and hit submit the url changes to "http://localhost:3000/users/sign_up?user%5Busername%5D=Madmax_123&user%5Bfname%5D=Maxwell&user%5Blname%5D=Ross&user%5Bdob%5D=2000-01-22&user%5Bemail%5D=madmax_maxwell%40outlook.com&user%5Bpassword%5D=madmax123&user%5Bpassword_confirmation%5D=madmax123&commit=Submit#"

i wasnt sure is this was a problem so i checked to see is any users were created after in console with @user = User.first but it keeps coming up >=nil

  <div class="space">
    <div class="wrapper"> 
      <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= render "devise/shared/error_messages", resource: resource %> 

            <div class="container2 right-panel-active" id="container2">
              <div class="form-container2 sign-up-container2">
                <form action="#" id="form">
                </form>
              </div>
              <div class="form-container2 sign-in-container2">
                <form action="#" id="form">
                  <h3 class="h1">Create Account</h3><br><br><br><br>
                  <%= f.text_field :username, autofocus: true,  placeholder:"User Name", class:"input"  %>
                  <%= f.text_field :fname, placeholder:"First Name", class:"input" %>
                  <%= f.text_field :lname, placeholder:"Last Name", class:"input"  %>
                  <%= f.date_field :dob, placeholder:"Dte of Birth", class:"input"  %>
                  <%= f.email_field :email, autofocus: true, autocomplete: "email",  placeholder:"Email", class:"input"  %>
                  <%= f.password_field :password, autocomplete: "new-password",  placeholder:"Password", class:"input"  %>
                  <%= f.password_field :password_confirmation, autocomplete: "new-password",  placeholder:"Confirm Password", class:"input"  %><br><br>
                  <%=f.submit "Submit", class:"button" %>
                </form>
              </div>
              <div class="overlay-container2">
                <div class="overlay">
                  <div class="overlay-panel overlay-left">
                    <h3 class="h1">Already have an Account?</h3><br> <br>
                    <%= link_to "Login", new_user_session_path, class:"ghost2" %>
                  </div>
                </div>
              </div>
            </div>

      <% end %>
    </div>
  </div>

I added the variables to my migration.

class CreateEvents < ActiveRecord::Migration[5.1]
  def change
    create_table :events do |t|
      t.decimal :price
      t.date :date
      t.string :venue
      t.string :ename
      t.text :description
      t.text :time
      t.integer :ticket

      t.timestamps
    end
  end
end

allowed for the variables to be passed in my application controller

require "application_responder"

class ApplicationController < ActionController::Base
  self.responder = ApplicationResponder
  respond_to :html

  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
    def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :fname, :lname, :dob])

    end
end

Event controller

class EventsController < ApplicationController
    def index

    end

    def show
        @event = Event.find(params[:event_id])

    end

    def new

    end

    def create
        @event = Event.new(event_params)
        @event.save
        redirect_to  events_url events_path
    end

    private def event_params
        params.require(:event).permit(:ename, :price, :date, :venue, :description, :time, :ticket)

    end

end

any help would be greatly appreciated.

mercredi 13 novembre 2019

How to solve AbstractController::DoubleRenderError

AbstractController::DoubleRenderError(Render and/or redirect were called multiple times in this action)

Task not running using whenever gem but runs in command prompt

Task File

require 'report.rb'
require 'rake'

    namespace :daily_report do
      desc "Daily Parakh Report"
      task daily_operator_report: :environment do
        puts "Daily report generation started"
        Reports::Report.generate_csv
        puts "finished"
      end
    end

schedule.rb file

env :PATH, ENV['PATH']

set :output, "home/rajdeep/police-api/log/whenever.log"

every 1.day, :at => "06:46PM" do # Many shortcuts available: :hour, :day, :month, :year, :reboot
  rake "daily_report:daily_operator_report"
end

When the clock hits the speicified time in whenever.rb file nothing happens, the task doesn't run, even whenever.log file is not created.

when i run rake daily_report:daily_operator_report it works.

Ruby key getting replaced, instead of a new key created

ruby 2.5

I have the following code:

test = {'primer' => 'grey'}
layers = ["tan","burgundy"]
fillers = ["blue","yellow"]
layers.each do |l|
    fillers.each do |f|
      test[l] = {} if !test.respond_to?(l)
      test[l][f] = {} if !test[l].respond_to?(f)
    end
end

When I run it in irb, I get the following:

{"primer"=>"grey", "tan"=>{"yellow"=>{}}, "burgundy"=>{"yellow"=>{}}}

I am expecting:

{"primer"=>"grey", "tan"=>{"blue"=>{},"yellow"=>{}}, "burgundy"=>{"blue"=>{},"yellow"=>{}}}

Why does the first respond_to produce the key, when the second one, replaces the previous key?

What am I missing?

mardi 12 novembre 2019

Rails server exits automatically. This is what i see below:

Macs-MacBook-Pro:try_app mac$ rails server /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/object/duplicable.rb:85: warning: BigDecimal.new is deprecated; use BigDecimal() method instead. => Booting WEBrick => Rails 4.2.3 application starting in development on http://localhost:3000 => Run rails server -h for more startup options => Ctrl-C to shutdown server /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated Exiting Traceback (most recent call last): 8483: from bin/rails:3:in <main>' 8482: from bin/rails:3:inload' 8481: from /Users/mac/try_app/bin/spring:15:in <top (required)>' 8480: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:inrequire' 8479: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in require' 8478: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in' 8477: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in load' 8476: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/bin/spring:49:in' ... 8471 levels... 4: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' 3: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' 2: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' 1: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in ': stack level too deep (SystemStackError)

jeudi 7 novembre 2019

Subtracting month from date is not giving correct value in ruby?

i am trying to subtract the month from Date its not giving accurate result

end_date = Date.parse("30-09-2019")
end_date - 1.months

returns 30 - aug - 2019

example 30-09-2019 - 1.month to give 31 - 08 - 2019
example 15-09-2019 - 1.month to give 14 - 08 - 2019

mercredi 6 novembre 2019

How to write url path for a .svg picture in css file on ruby on rails

I have a background-image with a svg file but it doesn't work at all, here is my css file :

&[data-icon=hourglass]::before {
    background-image: url("../../icons/hourglass.svg");
}

Do you know how to fix it ?

404 (Not Found) on my icon.svg - Ruby on rails app

I have an icon in my folder app > assets > medias > logo-footer.svg In my code it looks like this :

<img loading="lazy" class="footer__logo" src="app/assets/medias/logo-footer.svg" alt="Logo">

In my application I have an error in my console : GET http://127.0.0.1:3000/assets/icons.svg 404 (Not Found).

How can I set the right path to this icon.svg ?

Does call_backs with same name in parent and child classes need not to be called again

I had two methods with same name which is present in both parent and child class. But I the callback before_filter: method_name is called only in parent class and the before_filter: is not present in child class. But load_object is called in child class without call_back itself.

class Parent

before_filter: call

def call // end

end

class child < Parent

def call //But the method is called here without call_back end

end

There is no class is inherited from child.

Include scripts folder in my ruby on rails application

I try to integrate a script folder (with different file in .ts), located in my folder "javascript", in my ruby on rails application but when I make an alert in my index.ts, it doesn't work.

I have the balise javascript pack tag in my application.html.erb

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

I installed the gem 'typescript-rails' to run my .ts files I also tried to rename the file in .js.ts but it doesn't work either.

Do you have any idea how to run those files ?

lundi 4 novembre 2019

ActionView Template Error: Missing host to link to settings with no effect

I am updating an old rails 3 application to rails 4. When I run my tests with test unit I am getting the following error in my actionmailer:

ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

After some research I found that it requires the options

# in: environment.rb 
# Set the default host and port to be the same as Action Mailer.
Rails.application.default_url_options = Rails.application.config.action_mailer.default_url_options

# and in each environment an entry like this: 
# environments/test.rb 
config.action_mailer.default_url_options = { host: 'localhost', port: '3000' }

While I can confirm these settings are set in the rails console. The error does not go away.

2.0.0-p648 :002 > Rails.application.default_url_options
 => {:host=>"localhost", :port=>"3000"} 
2.0.0-p648 :003 > Rails.application.config.action_mailer.default_url_options
 => {:host=>"localhost", :port=>"3000"} 

dimanche 3 novembre 2019

Powered By Ruby on Rails

I had a site created. The developer thought it might be a good idea to put his link in the Powered By link at the bottom of my site How can i remove this? I have tried to remove it but i am not too familiar with Rails.