mardi 30 août 2022

Searching using a single integer in a hash whose keys are ranges in Ruby

I have this hash in Ruby:

hash = {
   0..25  => { low_battery_count:     13 }, 
  26..75  => { average_battery_count:  4 }, 
  76..100 => { good_battery_count:     4 }
}

Now, what is want is a method (preferably a built-in one) in which if I pass a value (integer e.g. 20, 30, etc), it should return me the value against the range in which this integer lies.

I have already solved it using each method but now, I want to optimize it, even more, to do it without each or map methods to reduce its complexity.

For Example:

method(3) #=> {:low_battery_count=>13}
method(35) #=> {:average_battery_count=>4}
method(90) #=> {:good_battery_count=>4}

lundi 29 août 2022

`auth_data=': couldn't set additional authenticated data (OpenSSL::Cipher::CipherError)

trying to create a new project on RoR and i get this error:

/Library/Ruby/Gems/2.6.0/gems/activesupport-6.1.6.1/lib/active_support/message_encryptor.rb:170:in `auth_data=': couldn't set additional authenticated data (OpenSSL::Cipher::CipherError)
    from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.1.6.1/lib/active_support/message_encryptor.rb:170:in `_encrypt'
    from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.1.6.1/lib/active_support/message_encryptor.rb:148:in `encrypt_and_sign'
    from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.1.6.1/lib/active_support/encrypted_file.rb:88:in `encrypt'
    from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.1.6.1/lib/active_support/encrypted_file.rb:61:in `write'
    from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.1.6.1/lib/active_support/encrypted_configuration.rb:29:in `write'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/generators/rails/credentials/credentials_generator.rb:30:in `add_credentials_file_silently'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/generators/rails/app/app_generator.rb:194:in `credentials'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/generators/app_base.rb:165:in `public_send'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/generators/app_base.rb:165:in `build'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/generators/rails/app/app_generator.rb:386:in `create_credentials'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/command.rb:27:in `run'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:127:in `invoke_command'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in `block in invoke_all'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in `each'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in `map'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in `invoke_all'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/group.rb:232:in `dispatch'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/base.rb:485:in `start'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/commands/application/application_command.rb:26:in `perform'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/command.rb:27:in `run'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:127:in `invoke_command'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/thor-1.2.1/lib/thor.rb:392:in `dispatch'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/command/base.rb:69:in `perform'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/command.rb:48:in `invoke'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/lib/rails/cli.rb:18:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:65:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:65:in `require'
    from /Users/carolinecagnin/.gem/ruby/2.6.0/gems/railties-6.1.6.1/exe/rails:10:in `<top (required)>'
    from /usr/bin/rails:22:in `load'
    from /usr/bin/rails:22:in `<main>'

Tried almost everything i found on internet and still can't solve it... I'm just trying to study lol I also use mac OS Monterey

rails - render form fields dynamically

I Have a Simple Form field with year and month field in the form.

<%= form_for :calender, remote: true do |f| %>
  <%= f.select :year, @year_array %>
  
  <% if :year == DateTime.now.strftime("%Y").to_i %>
    <%= f.select :month, @month_array[0..Date::MONTHNAMES.index(DateTime.now.strftime("%B"))-1] %>
  <% else %>
    <%= f.select :month, @month_array %>
  <% end %>
  
  <%= f.submit "Submit" %>
<% end %>
@year_array data contains in format [[2020, 2020], [2021, 2021], [2022, 2022]]

@month_array data contains in format 
[["January", "Jan"], ["February", "Feb"], ["March", "Mar"], ["April", "Apr"], ["May", "May"], 
 ["June", "Jun"], ["July", "Jul"], ["August", "Aug"], ["September", "Sep"], ["October", "Oct"], 
 ["November", "Nov"], ["December", "Dec"]]

How can I render this form dynamically. what I mean is when the user select the current year then month only render up to current month from January rather than whole array.

dimanche 28 août 2022

Why is my ActionMailer throwing up Unpermitted parameter: :user?

So im trying to set up action mailer and I followed along with the official docs https://guides.rubyonrails.org/action_mailer_basics.html...Now when I try to sign up I get an error

Started POST "/signup" for 127.0.0.1 at 2022-08-28 15:12:10 +0530
Processing by UsersController#create as */*
  Parameters: {"name"=>"Yash", "email"=>"yashsawant932@gmail.com", "password"=>"[FILTERED]", "user"=>{"name"=>"Yash", "email"=>"yashsawant932@gmail.com"}}
Unpermitted parameter: :user
  TRANSACTION (0.1ms)  BEGIN
  ↳ app/controllers/users_controller.rb:5:in `create'
  User Exists? (0.8ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "yashsawant932@gmail.com"], ["LIMIT", 1]]
  ↳ app/controllers/users_controller.rb:5:in `create'
  TRANSACTION (5.4ms)  ROLLBACK
  ↳ app/controllers/users_controller.rb:5:in `create'
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash (0.04ms)
Completed 422 Unprocessable Entity in 313ms (Views: 0.3ms | ActiveRecord: 6.3ms | Allocations: 5065)


Pls check out my code and let me know what im missing ?Also is my action mailer set up properly User controller

class UsersController < ApplicationController
  rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response
  skip_before_action :authorize, only: [:create]
   def create
      user = User.create!(user_params)
      session[:user_id] = user.id
      render json: user, status: :created
      UserMailer.with(user: @user).welcome_email.deliver_later
    end
    
    def show
      render json: @current_user
    end

    def index
      user=User.all 
      render json: user
    end


  private     
  def user_params
      params.permit(:name,:email,:password)

  end
  def render_unprocessable_entity_response(invalid)
    render json: { errors: invalid.record.errors.full_messages }, status: :unprocessable_entity
  end
end

Application mailer

class ApplicationMailer < ActionMailer::Base
  default from: 'from@example.com'
  layout 'mailer'
end


Usermailer.rb

class UserMailer < ApplicationMailer
    default from: 'welcome@bigapple.com'

    def welcome_email
      @user = params[:user]
      @url  = 'http://example.com/login'
      mail(to: @user.email, subject: 'Welcome to Big Apple Explorer')
    end
end

views/user_mailer/welcome_email.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Welcome to bigapple.com, <%= @user.name %></h1>
    <p>
      You have successfully signed up  & we are soo happy you are here.
      Now onwards you will get regular updates about the app.Feel free to 
      email back for any issues.
    </p>
   
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>

text.erb

Welcome to bigapple.com, <%= @user.name %>

You have successfully signed up  & we are soo happy you are here.
Now onwards you will get regular updates about the app.Feel free to 
email back for any issues.


Thanks for joining and have a great day!

Also this is my app controller

class ApplicationController < ActionController::API
  include ActionController::Cookies
  rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response
  before_action :authorize
  
   private
   def authorize
     puts "hello",session[:user_id]
     @current_user = User.find_by(id: session[:user_id])
      render json: { errors: ["Not authorized"] }, status: :unauthorized unless @current_user
   end
 
   def render_unprocessable_entity_response(exception)
     render json: { errors: exception.record.errors.full_messages }, status: :unprocessable_entity
   end
end

other than this i added nothing in my code becuz this was the online thing given no config settings nothing...

samedi 27 août 2022

RoR + Sidekiq background processes

I'm trying to get my list to go closed when the End Date is met. Could anyone help me? I'm using sidekiq for background processes and I already have my list passing closed status, but not when it reaches the end date.

My table

create_table "lists", force: :cascade do |t|
t.integer "user_id"
t.binary "uuid", limit: 36
t.string "name"
t.string "description"
t.datetime "end_date"
t.integer "status", default: 1
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_lists_on__user_id"

I did this in the sidekiq so that my list goes to the disabled state

    class HardJob
    include Sidekiq::Job

    def perform(list_id)
     list = List.find list_id
     list.disabled!

     return 0
    end
   end

vendredi 26 août 2022

nokogiri : finding a node in html document by their styling

I am currently working in a web scrapping project with ruby on rails and below is the web-page link I am working on.

https://www.livelaw.in/top-stories/supreme-court-civil-suit-maintainable-jurisdiction-scope-sau-rajani-vs-sau-smita-2022-livelaw-sc-702-207475?infinitescroll=1

I have fetched all the (.story p ) from this page and particularly want to remove the last tag having background-color:rgb(255,255,0) Here's the thing I want to remove

I want to select the tag using the custom styling it has. picture for clarity

I have tried everything and not able to do so. I there any other way I can select the desired text and remove it from the doc.

jeudi 25 août 2022

Ruby on Rails ActiveRecord filter issue

I have a problem.

Problem description: I have table Projects and table Assets. I need show Projects only where model_aseets is exists only.

Example code My query:

select  s3_object_key,  a.id from projects
left join assets a on projects.id = a.project_id
where asset_category =2
projects = Project.where(Asset.ar_model.exists)

Get an error:

"status": 500,
"error": "Internal Server Error",
“exception": "#<NoMethodError: undefined method `exists' for #<ActiveRecord::Relation

Could someone help, please. Thanks

mercredi 24 août 2022

How to format a response to have columns and rows in array?

I have an API response and return the following format.

AccountId Requests
1         3
2         67
3         50
          10
-- 10 batches, 10 datasources

However, when I added this response to an empty array, it changed to the below format.How can I change the format in the array to columns and rows?

["\e[1mAccountId    requests    \n\e[m1    3    \n2    67    \n3    50    \n    9.   \n-- 10 batches, 10 datasource\n"]   

mardi 23 août 2022

How to group user by create date in rails? [duplicate]

How to group user by create date in rails ?

<User... created_at: '2022-03-27 21:32:00' >
<User... created_at: '2022-03-28 19:57:00' >
<User... created_at: '2022-03-28 07:39:00' >
<User... created_at: '2022-03-29 02:23:00' >
<User... created_at: '2022-03-29 18:44:00' >

The result I want is

{ 
'2022-03-27' : [<User... created_at: '2022-03-27 21:32:00' >, <User... created_at: '2022-03-27 18:30:00' >],
'2022-03-28' : [<User... created_at: '2022-03-28 19:57:00' >
<User... created_at: '2022-03-28 07:31:00' >],
'2022-03-29' : [<User... created_at: '2022-03-29 02:23:00' >
<User... created_at: '2022-03-29 18:44:00' >] 
}

Ruby print JSON value - no implicit conversion of String into Integer

I'm trying to print only the value of a JSON and I'm getting the error no implicit conversion of String into Integer.

Any idea how I can resolve this?

puts test.class

Azure::Armrest::ArmrestCollection

Here is the output of the varaible and I want to print only the quantity value.

puts test

[----] I, [2022-08-23T08:59:20.279357 #550:bc494]  INFO -- automation: Method STDOUT: {"id":"/subscriptions/123456/providers/Microsoft.Commerce/UsageAggregates/Daily_BRSDT_20220801_0000","name":"Daily_BRSDT_20220801_0000","type":"Microsoft.Commerce/UsageAggregate","properties":{"subscriptionId":"123456","usageStartTime":"2022-07-31T00:00:00+00:00","usageEndTime":"2022-08-01T00:00:00+00:00","meterName":"Data Transfer Out","meterRegion":"North America","meterCategory":"Bandwidth","meterSubCategory":"Inter-Region","unit":"1 GB","instanceData":"{\"Microsoft.Resources\":{\"resourceUri\":\"/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Compute/virtualMachines/ubuntu975\",\"location\":\"eastus\",\"additionalInfo\":{\"PipelineType\":\"v2\",\"DataTransferDirection\":\"DataTrOut\"}}}","meterId":"dbefcfc1-e3f6-409b-be6d-9cd7b00724a5","infoFields":{},"quantity":9.052455425262451e-07}}
[----] I, [2022-08-23T08:59:20.280435 #550:bc494]  INFO -- automation: Method STDOUT: {"id":"/subscriptions/123456/providers/Microsoft.Commerce/UsageAggregates/Daily_BRSDT_20220801_0000","name":"Daily_BRSDT_20220801_0000","type":"Microsoft.Commerce/UsageAggregate","properties":{"subscriptionId":"123456","usageStartTime":"2022-07-31T00:00:00+00:00","usageEndTime":"2022-08-01T00:00:00+00:00","meterName":"Dynamic Public IP","meterCategory":"Virtual Network","meterSubCategory":"IP Addresses","unit":"1 Hour","instanceData":"{\"Microsoft.Resources\":{\"resourceUri\":\"/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/publicIPAddresses/Ubuntu975-publicIp\",\"location\":\"eastus\",\"additionalInfo\":{\"IpAddress\":\"20.25.57.9\",\"PlatformType\":\"V2-Agg\"}}}","meterId":"f114cb19-ea64-40b5-bcd7-aee474b62853","infoFields":{},"quantity":1.0}}

puts test["properties"]["quantity"]

[----] E, [2022-08-23T08:59:28.949873 #544:b6620] ERROR -- automation: <AEMethod getcostusage> [no implicit conversion of String into Integer]
/CloudForms_Essentials/Integration/Azure/StateMachines/getCostUsage:79:in `[]'
/CloudForms_Essentials/Integration/Azure/StateMachines/getCostUsage:79:in `<main>'
[----] I, [2022-08-23T08:59:28.974301 #544:ac260]  INFO -- automation: <AEMethod [/CloudForms_Essentials/Integration/Azure/StateMachines/getCostUsage]> Ending

If I try JSON.parse(test) then I get this error.

[----] E, [2022-08-23T09:18:39.022825 #553:bcaac] ERROR -- automation: <AEMethod getcostusage> [no implicit conversion of Azure::Armrest::ArmrestCollection into String]

dimanche 21 août 2022

Recursive Function on Ruby on Rails

I have a mysql table that I am tracking relating items. (this table belong to Artilce table) [this is the datastructer from mysql][1] [1]: https://ift.tt/YDls7aO

how can I generate a json from Ruby that looks like this. (I need that for D3JS visualisation tree)

{
"id":1,
"art_type":"V",
"children":[
{
    "id":7,
    "art_type":"V",
    "children":[
        {
            "id":9,
            "art_type":"V",

        },
        {
            "id":10,
            "art_type":"V",
        }
    ]
},
{
    "id":8,
    "art_type":"V",
    "children":[
        {
            "id":11,
            "art_type":"R"
        },
        {
            "id":12,
            "art_type":"V"
        },
        {
            "id":13,
            "art_type":"V"
        }
    ]
}
]

}

Rails API with query string time stamp

I am continuing on creating an API with ruby on rails. I have got the basis of it done by following https://levelup.gitconnected.com/7-steps-to-create-an-api-in-rails-2f984c7c4286

but instead of Forests and trails, I am using restaurants and Comments as my models. Restaurants has many comments and comments has one restaurant.

Right now I can call on: http://localhost:3000/api/v1/restaurants/1?by_updated_at=2022-08-20T10:00:00.000Z

This will send me the exact comments that updated at that given time.

[
    {
        "id": 1,
        "restaurant_id": 1,
        "comment": "good.",
         "age": 28,
        "created_at": "2022-08-20T10:00:00.000Z",
        "updated_at": "2022-08-20T10:00:00.000Z"
    }
]

I would like to go further and say if the user wants to find the updated time of a comment for restaurant 1 like: http://localhost:3000/api/v1/restaurants/1?by_updated_at=2022-08-20T12:00:00.000Z AND there is no record with the exact updated_at time given:

How do I get the record that is closest to it? So that the record shown is then:

    {
        "id": 2,
        "restaurant_id": 1,
        "comment": "very good.",
         "age": 25,
        "created_at": "2022-08-20T12:30:00.000Z",
        "updated_at": "2022-08-20T12:30:00.000Z"
    }
]

Right now my code looks like: restaurants_controller.rb

  def show
    @restaurant = Restaurant.find(params[:id])
    @comments = apply_scopes(@restaurant.comments).first
    render json: @comments
  end

comment.rb (model) with

gem 'has_scope'

class Comment < ApplicationRecord
  belongs_to :restaurant
  scope :by_updated_at, ->updated_at { where(updated_at: updated_at)}

I looked at the first answer of this one: How to pass query params to Rails API controller? in combination with: find record closest to a given time in ruby on rails

and thought maybe I need to be updating the scope in the comment model to do something like this

  scope :by_updated_at, ->updated_at { where('updated_at>= ? AND updated_at <= ?', updated_at - 600, updated_at + 600).order('ABS(updated_at - updated_at)'), updated_at }

this is obviously wrong but now I am confused by the many updated_ats and not sure how to implement

note: there are many more records in this.

samedi 20 août 2022

Azure - Get Billing cost for specified date using Ruby

How can I get the billing cost for specified date using ruby? I tired following this document but it returns nothing. I want to fetch the cost for last 15 days or 30 days.

I'm not sure if I should enable something in portal if this needs to work?

https://www.rubydoc.info/gems/azure-armrest/0.3.2/Azure/Armrest/Billing/UsageService

The following code returns nothing. No errors either.

require 'azure/armrest'

conf = Azure::Armrest::Configuration.new(
  :client_id       => '123456',
  :client_key      => '123456',
  :tenant_id       => '123456',
  :subscription_id => '123456'
)  



BILLING = Azure::Armrest::Billing::UsageService.new(conf)  
  
options = {:reportedStartTime => '2022-07-01T00:00:00Z', :reportedEndTime => '2022-07-31T00:00:00Z', :aggregationGranularity  => 'Daily', :ShowDetails => 'true'}
    

test = BILLING.list(options)

mercredi 17 août 2022

return the object as per custom weight in ruby

I have a use case where I have the array of object and I want to return the particular object based on the type. But the interesting part is that if one type is present then it should return the specific object and if it is not present it should return the object which has 2nd type and so on.

For me, priority is if type: video is present is should be returned and if it is not present then it should check further for type: file, if it is present then object with type:file should returned.

Ex: a = [<id:1, type:'video', format:'mp4'>, <id:2, type:'audio', format:'mp3'>,
         <id:3, type:'file', format:'txt'>, <id:4, type:'exe', format:'exe'>]

In response, I should get the object of index 0 if type: video is present in a, else it should return object of index 2 if type: file is present and then it should return object of index 1.

mardi 16 août 2022

undefined method `will_save_change_to_address

I am new to coding and a friend and I are making a website that has a map with markers. For some reason it's working when she pulls the master branch but when I pull origin master on GitHub I get errors and no markers. Does anyone know why it works on one devise but not on another? We have been constantly running into this issue.

product model

class Product < ApplicationRecord
  belongs_to :user
  has_many :bookings, dependent: :destroy
  validates :name, presence: true
  validates :category, presence: true
  has_one_attached :photo
  geocoded_by :address
  after_validation :geocode, if: :will_save_change_to_address?
  include PgSearch::Model
  pg_search_scope :search_by_name_and_category,
  against: [ :name, :category ],
  using: {
    tsearch: { prefix: true } # <-- now `superman batm` will return something!
  }
end

product controller

def index
    if params[:query].present?
      @products = Product.search_by_name_and_category(params[:query])
    else
      @products = Product.all
      @markers = @products.geocoded.map do |product|
        {
          lat: product.latitude,
          lng: product.longitude
        }
      end
    end
  end

private

  def product_params
    params.require(:product).permit(:name, :category, :price, :description, :address)
  end

view

<div class="card-product-container">
  <div class="cards">
    <% @products.each do |product| %>
      <div class="card-product">
        <%= link_to product_path(product.id) do %>
        <img src="https://source.unsplash.com/random/?<%= product.name %>" />
          <div class="card-product-footer">
            <div style="text-decoration:none;">
              <h2><%= product.name %></h2>
              <p>Owner <%= product.user.first_name %></p>
            </div>
          <h2><%= product.price %></h2>
          </div>
        <% end %>
      </div>
    <% end %>
  </div>

    <div style="width: 100%; height: 600px;"
      data-controller="map"
      data-map-markers-value="<%= @markers.to_json %>"
      data-map-api-key-value="<%= ENV['MAPBOX_API_KEY'] %>">
    </div>
</div>

schema

create_table "products", force: :cascade do |t|
    t.string "name"
    t.string "category"
    t.boolean "available"
    t.string "image"
    t.text "description"
    t.integer "price"
    t.bigint "user_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.float "latitude"
    t.float "longitude"
    t.index ["user_id"], name: "index_products_on_user_id"
  end

map controller

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static values = {
    apiKey: String,
    markers: Array
  }

  connect() {
    mapboxgl.accessToken = this.apiKeyValue

    this.map = new mapboxgl.Map({
      container: this.element,
      style: "mapbox://styles/mapbox/streets-v10"
    });
    this.#addMarkersToMap()
    this.#fitMapToMarkers()
  }

  #fitMapToMarkers() {
    const bounds = new mapboxgl.LngLatBounds()
    this.markersValue.forEach(marker => bounds.extend([ marker.lng, marker.lat ]))
    this.map.fitBounds(bounds, { padding: 70, maxZoom: 15, duration: 0 })
  }

  #addMarkersToMap() {
    this.markersValue.forEach((marker) => {
      new mapboxgl.Marker()
        .setLngLat([ marker.lng, marker.lat ])
        .addTo(this.map)
    })
  }
}

dimanche 14 août 2022

how to use .map{|x| x[1]} with group_by_period in rails

I want to show data for the past 14 days where requests have occurred which is showing on map

 @maintenance_count = Maintenance.where(property_id: property_ids)
.where("created_at >= ?", start_date)
.group_by_period(params[:day_month], :created_at, series: true, format: date_format, 
 last: params[:duration].to_i)
.count.map{|x| x[1]}

this is taking params from URL i assigned like this

 a.dropdown-item  href="?day_month=day&duration=14" 14 Days
a.dropdown-item  href="?day_month=week&duration=8" 8 weeks
a.dropdown-item  href="?day_month=month&duration=12" 12 months
 a.dropdown-item  href="?day_month=year&duration=2" 2 years

i want to show for past 14 days when params are empty but i don't know how this array working with map

labels: @maintaince_ending_labels,
              datasets: [
                {                    
                    data: @maintenance_count
                },
              ]

 if params[:day_month] == "day"
  start_date = (Date.today - params[:duration].to_i.day).beginning_of_day
  date_format = '%a %d'

mercredi 3 août 2022

apply: private method open called for URI:Module (NoMethodError)

/home/felipe/.rvm/gems/ruby-2.2.10/gems/thor-1.2.1/lib/thor/actions.rb:226:in apply': private method open' called for URI:Module (NoMethodError)