samedi 29 mai 2021

Single Foregn Key references multiple Tables [Rails6]

I have an application with "Categories" "Players" & "Matches".

I want to create a new Table: "Suggestions", with the params: [name: string, description:text, type:integer, element_id:integer]. Users will be able to create "Suggestions" for a Player, Category or a Match. Where the type:integer indicates if it's a "Category Suggestion"-> 1, "Player Suggestion"->2, "Match Suggestion"-> 3. My question is regarding the "element_id" which is meant to be a foreign_key although this foreign key can be from "Category", "Player" or "Match", depending the "type" of the Suggestion. So basically the question is:

How do I reference Multiple tables with only one foreign key. I though about a solution in the models where I just place the foreign key there, but im not sure if this can cause problems in my application. Also I thought about creating 3 tables CategorySuggestions PlayersSuggestions and MatchesSuggestions but that would just be overkill and I wouldn't like that so much.

vendredi 28 mai 2021

I got the following error while running gem install mysql2 on windows 10

I downloaded and installed ruby from this https://rubyinstaller.org/downloads/ -> Ruby+Devkit 2.7.3-1 (x64) and follow the installation steps. but I got a error when I tried to install mysql2 for rails using

gem install mysql2

ruby version is 2.7.3p183

rails version is 6.1.3.2

gem version is 3.1.6

ERROR: Error installing mysql2: The last version of mysql2 (>= 0) to support your Ruby & RubyGems was 0.5.3. Try installing it with gem install mysql2 -v 0.5.3 mysql2 requires Ruby version >= 2.2, < 2.7.dev. The current ruby version is 2.7.3.183.

I tried gem install mysql2 -v 0.5.3 but got same error.

I installed mysql before running this command, and I also have mysql on XAMPP. I installed MYSQL using mysql-installer-web-community-8.0.25.0

samedi 22 mai 2021

How to blacklist certain character combinations from long text input using validations?

In my Rails app users can create their own email templates. I need to validate that only certain placeholders can be used, like to:

Dear {first_name} {last_name},

Please find enclosed our quote.

Best regards

John Doe

Bogus placeholders like {middle_name} or {foo} or even single brackets like { or } should be marked as invalid.

How can this be done using Ruby or Regex?

How to install ruby on Ubuntu on wsl?

I was trying to install ruby on ubuntu using rvm install "ruby-2.7.0". I was following the instruction on this question https://askubuntu.com/questions/91543/apt-get-update-fails-to-fetch-files-temporary-failure-resolving-error but I am still facing this issue. How can I get this issue resolved.

Err:1 http://security.ubuntu.com/ubuntu focal-security InRelease
      Temporary failure resolving 'security.ubuntu.com'
    Err:2 http://archive.ubuntu.com/ubuntu focal InRelease
      Temporary failure resolving 'archive.ubuntu.com'
    Err:3 http://archive.ubuntu.com/ubuntu focal-updates InRelease
      Temporary failure resolving 'archive.ubuntu.com'
    Err:4 http://archive.ubuntu.com/ubuntu focal-backports InRelease
      Temporary failure resolving 'archive.ubuntu.com'
    Reading package lists... Done
    W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal/InRelease  Temporary failure resolving 'archive.ubuntu.com'
    W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal-updates/InRelease  Temporary failure resolving 'archive.ubuntu.com'
    W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal-backports/InRelease  Temporary failure resolving 'archive.ubuntu.com'
    W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/focal-security/InRelease  Temporary failure resolving 'security.ubuntu.com'
    W: Some index files failed to download. They have been ignored, or old ones used instead.
    Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    Calculating upgrade... Done
    The following packages have been kept back:
      ubuntu-advantage-tools
    The following packages will be upgraded:
      initramfs-tools initramfs-tools-bin initramfs-tools-core libssl1.1 openssl sosreport
    6 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
    Need to get 2252 kB of archives.
    After this operation, 4096 B of additional disk space will be used.
    Do you want to continue? [Y/n] n

jeudi 20 mai 2021

rails 3.1 undefined method rescue_action_locally is making me miserable

I'm stumped.

I inherited a Rails 3.1 app and I'm getting this weird error...

NoMethodError - undefined method `rescue_action_locally' for #<AssignmentsController:0x000000042583d0>:
  app/controllers/application_controller.rb:362:in `process_exception'

And error output is pointing me to line 362 ...

    def process_exception(exception)
      authorize
      set_cashier
      if rescue_as_normal
        ret = rescue_action(exception)
      else
        ret = rescue_action_locally(exception)  <--- but why is this exploding?
      end
      if request and request.xhr?
        response.content_type = Mime::JS
      end
      return ret
    end

I'm on rbenv and my ruby is 1.9.3-p551

If I function-click this in Rubymine I can see this exist inside action_dispatch/middleware/show_exeptions.rb:80 ... So I know the thing is there.

I have no idea why this is exploding. Any clues appreciated.

bad value for range (ArgumentError) in ruby

#I get the desired output but the interpreter throws an ArgumentError-bad value for range ?

Q)Given an array of integers, for each integer output all integers from 1 to that integer; e.g. if the integer was 5, you would output 1, 2, 3, 4, 5.

Solution:

numbers = [7, 3, 5, 2, 1, 8, 4]

counter = 0 loop do num = numbers[counter] (1..num).each do |ele| puts ele

end 

counter += 1

end

mercredi 19 mai 2021

Using aggregate query how can I get ids of existing record ( rails mongodb )

I have a bunch of video records and I want to find out the video ids of this record.

I had try collect, pluck and distinct as well but it's tacking to much time for execute. so I want to use aggregate query. but I don't know how to write this query. If any one knows please help me out.

videos = Video.all
video_ids = videos.pluck(:id)

Thanks :)

What is the point in Ruby's String#freeze method if one can still reassign a new value to the frozen variable?

I'm trying to understand the use of # frozen_string_literal: true in RoR and I understand the freeze method protects the frozen strings from modification up to some extend, but what's the point given that it's as easy to change the string as just reassigning the value? I would expect freeze to block reassignment too if the idea is protecting the variable from modification.

2.7.2 :001 > str = "string"
 => "string"
2.7.2 :002 > str.freeze
 => "string"
2.7.2 :003 > str.frozen?
 => true
2.7.2 :004 > str << "fails"
Traceback (most recent call last):
        4: from /Users/dev/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `<main>'
        3: from /Users/dev/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `load'
        2: from /Users/dev/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
        1: from (irb):4
FrozenError (can't modify frozen String: "string")
2.7.2 :005 > str = "stringfails... but this is fine?!"
 => "stringfails... but this is fine?!"
2.7.2 :006 > str
 => "stringfails... but this is fine?!"

I feel like I'm getting confused between freezing the string versus freezing the variable, but a lot of resources mention constants and compare the behaviour to them, so I'm unsure if the idea is to freeze the string assigned to the variable or the variable itself.

lundi 17 mai 2021

Time complexity of creating a Hashie::Mash object

I want to understand how expensive is to create a new Hashie::Mash. Does calling Hashie::Mash.new(object_hash) creates a deep copy of the "object_hash"

Example: What is the time complexity of below given array size is M and emp object has N key value pair.

array.map { |emp| Hashie::Mash.new(emp)

Will it be O ( M x N ) ?

Note: I am trying to understand this from the performance perspective and N can be large won't be constant because of the nested hash. In case you want to look at the structure of emp ( employee which can have nested employees is)

{
"id"=> 1,
.
.
"nested_employee" => [

   {
    "id"=> 12,
     .
     .
   },
    {
    "id"=> 13,
     .
     .
   }]
.
.
}

Verfiy the same input string is mobile number or email address In ruby

For example, I am getting the Input

params[::email_or_mobile]

How can I verify the number is an email or mobile number The input params maybe sample@gmail.com or +91987778989

samedi 15 mai 2021

I have a problem with my "creation" action

I have an articles route in my project. I created a Post model. I don't know if there are conflicts in that This is my code:

class PagesController < ApplicationController


  def articles
    @posts = Post.all
  end

  def new
    @post = Post.new
  end

  def show
   @post = Post.find(params[:id])
  end

  def create
    @post = @Post.new(post_params)
    @post.save
    redirect_to article_path(@post)
   end

  def contacts
  end

  private

  def post_params
    params.require(:post).permit(:title, :author, :body)
  end


end

This is my error:

ActionController::ParameterMissing in PagesController#create
param is missing or the value is empty: post
Extracted source (around line #35):

              

  def post_params
    params.require(:post).permit(:title, :author, :body)
  end

This my routes file:

Rails.application.routes.draw do root 'pages#index' get 'about', to: 'pages#about' get 'services', to: 'pages#services' get 'articles', to: 'pages#articles' get 'articles/new', to: 'pages#new' get 'articles/:id', to: 'pages#show', as: 'article' post 'articles', to: 'pages#create' get 'contacts', to: 'pages#contacts' end

dimanche 9 mai 2021

How to fix warning: constant Gem::RubyGemsVersion is deprecated

I'm starting an app on an old production server and I'm getting...

.../config/boot.rb:71: warning: constant Gem::RubyGemsVersion is deprecated

What the heck is that and any ideas on how I can fix it. (Google is not being my friend right now)

vendredi 7 mai 2021

How to invoke a controller method from my Javascript?

I have a JS function in my erb file as such

....

function sendData(){
  let payload = {'user':'1'};
  //call controller function with payload here
}

.... My controller is like this :

def myMethod(payload)
    @page_title = 'Request an Disti RMA'
    logger.info "****Inside the generate RMA Method"
end

Can someone please tell me how to call the controller method with variables from the JS function?

mercredi 5 mai 2021

undefined method `constantize' for Resque:Module Did you mean? constants

I am getting undefined method constantize' for Resque:Module Did you mean? constantserror while clicking onSchedulefromresquepage i.e/resque/schedule` I started getting this error few days back. I haven't changed anything in the code.

Below is the gem code https://github.com/resque/resque-scheduler/blob/v2.0.0.g/lib/resque_scheduler/server.rb#L17

I am using below gems for resque:

gem 'resque', '~> 1.25.0', :require => 'resque/server'
gem 'resque-fairly', '~> 1.1.0'
gem 'resque-scheduler', '2.0.0.g'
gem 'rufus-scheduler', '2.0.24'
gem 'resque-retry', '0.2.2'
gem 'resque-lock', '1.0.0'

I tried to update the resque-scheduler version >= 2.0.1 , then the Schedule button disappears.

I am using ruby 2.3.0 and rails 3

enter image description here

Below is the error image Error Image

mardi 4 mai 2021

NameError: undefined method `tables' for class `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter'

I have an old 3.1 app I'm working on

I get this error when I run "rake db:schema:dump"...

"NameError: undefined method `tables' for class `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter'"

I am stumped by this and I'm not sure where to start looking for a solution. The almighty google is coming up short. Any suggestions greatly appreciated.

how to remove input form consol in ruby

#input :

puts "hello what is your name " name = gets.chop

puts "Hello #{name} nice to meet you!"

#output:

hello what is your name rat Hello rat nice to meet you!

when i execute my script it shows :hello what is your name then i wrote name :ex rat when i wrote >>rat.it directly prints the output : Hello rat nice to meet you! . but i want to clear first name =rat >>and then print output. so how can i ?

Crud modal popups in rails

I tried to implement crud modal popups in rails but I tried my times I didn't get the proper output in some other website it shows only of new.html.erb I need to give modal popups for show and action