jeudi 30 juin 2022

Building an Interactive Site with React.js and Devise Authentication

I’m having a hard time trying to explain what it is I’m trying to do, but here I go:

I am building a site on a React.js framework and using Devise for authentication. I am trying to figure out how I can display user’s data on a Dashboard or Home page and have other users’ data be connected so I can see any user's data, not just the user who is signed in. So far, I can create data (fill out a form and will see the results) and see what I created, but I want to also be able to see what another user creates. I’m building a site where participants can add in miles they cover in a week, but would like them to also see how they stack up against others. Are there any good tutorials or projects that anyone can point me towards? Thanks! Stephanie

source: https://github.com/smedlin13/WAS_Hustle_Board

mardi 28 juin 2022

how to Include a module from app/lib folder

I am getting an error while trying to load a class from module which is present in app/lib folder.

I had made changes according to it

Controller

class SchemasController < ApplicationController
  # include Schemas
  # require './app/lib/api'
  include Operator
end

class under module which I have to include:

# frozen_string_literal: true

module API
  module AnalyticsQueryBuilderMetadataService
    class Operator
      @base_uri = ServiceConfig[:analytics_query_builder_metadata_service_uri]

      def self.where(params = {})
        response = API::Connection.connect_with_oauth1a(@base_uri).get('operators', params)

        response.body
      end
    end
  end
end

application.rb:

require_relative "boot"


# Pick the frameworks you want:
require 'action_controller/railtie'
require 'active_job/railtie'
require 'action_cable/engine'
require 'action_mailer/railtie'


# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module AnalyticsQueryBuilder
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 7.0
    config.autoload_paths += %W(#{config.root}/lib)
    # config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    config.before_configuration do
      env_file = File.join(Rails.root, 'config', 'local_env.yml')
      if File.exist?(env_file)
        YAML.safe_load(File.open(env_file)).each do |key, value|
          ENV[key.to_s] = value
        end
      end
    end
    Rails.logger = Logger.new($stdout)

    config.exceptions_app = routes
 
  end
end

The structure of file:

https://i.stack.imgur.com/gM16x.png

How to include it in Controller

Directly download from a link and upload file to GCS

Is there a way to download a MP4 file directly and store on Google bucket. We have a use-case to get a file URL to download and upload it on cloud. However, since file size can be more than 1 GB, it is not feasible to download in local storage first and then upload the file to cloud bucket. We are specifically looking for google cloud storage to upload files and solution should be specific to same.

Some Ref doc we found but does not look like the feasible solution as it uploads file from local storage not directly from link.

https://googleapis.dev/ruby/google-cloud-storage/latest/Google/Cloud/Storage.html

https://www.mydatahack.com/uploading-and-downloading-files-in-s3-with-ruby/

samedi 25 juin 2022

Metamask-mobile browser not working on server side sessions and exchange the session ids via cookies

The cookies functionality have been broken for the past releases. This bug is causing a lot of issues to the developer community and not allowing Dapps to work properly with MetaMask mobile. We can confirm that the android version of metamask-mobile browser seem to have a problem with websites that use server side sessions and exchange the session ids via cookies. It also affects websites developed with Ruby On Rails session handling.

For a reproducible test you can see the problem on https://matic.art

vendredi 24 juin 2022

(can't activate mysql2 (~> 0.3.10), already activated mysql2-0.5.4. Make sure all dependencies are added to Gemfile.)

Ubuntu 20.04 Rails 3.2.22.5 Ruby 2.3.7 mysql2 8.0.29

  • Above are the versions that currently i'm using for my project(app).
  • In Gemfile mysql2 version is 0.3.18 but this version throwing me errors and not allowing me to run complete bundle.
  • But, when i'm trying to run bundle with different version of mysql2 gem like 0.5.4, bundle successfully running but after that when i try to create db(database) or to start server this above error mentioned in question appears.

Anyone please help me out in this regard if you guys have any idea about that. Thanks in advance

mardi 21 juin 2022

Since switching to Ruby 3, migrations fail with ArgumentError: wrong number of arguments

  def up
    change_table :onboardings, bulk: true do |t|
      t.remove :name
      t.remove :address
      t.remove :occupation
      t.remove :nickname
    end
  end

this returns

ArgumentError: wrong number of arguments (given 2, expected 1)

It amazes me how hard it's been to find any kind of documentation on how this should be formatted now. Any help would be greatly appreciated.

Ruby/Heroku app errors "We're sorry, but something went wrong" troubleshooting

I am trying to setup an Elo rating system for my local 8 ball pool league using: https://github.com/elovation/elovation

The only changes I have made to above repo prior to deployment are specifying heroku:stack-18 in app.json and running bundle install after specifying to use https:// instead of git://

I have deployed my app to Heroku without error but when loading my app I get a "We're sorry, something went wrong page"

After deployment I have ran heroku run rake db:migrate and heroku restart but my error persists

I have included below output of heroku logs ; any help with the below errors would be greatly appreciated as I am not particularly familiar with Ruby or Heroku postgres.

2022-06-21T12:54:08.886300+00:00 app[web.1]: I, [2022-06-21T12:54:08.886206 #9]  INFO -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13] Processing by DashboardController#show as HTML
2022-06-21T12:54:08.888800+00:00 app[web.1]: D, [2022-06-21T12:54:08.888726 #9] DEBUG -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]   Player Load (0.5ms)  SELECT "players".* FROM "players"
2022-06-21T12:54:08.889854+00:00 app[web.1]: I, [2022-06-21T12:54:08.889789 #9]  INFO -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]   Rendering dashboard/show.html.erb within layouts/application
2022-06-21T12:54:08.891005+00:00 app[web.1]: D, [2022-06-21T12:54:08.890942 #9] DEBUG -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]   Game Load (0.5ms)  SELECT "games".* FROM "games" ORDER BY updated_at DESC
2022-06-21T12:54:08.891468+00:00 app[web.1]: I, [2022-06-21T12:54:08.891374 #9]  INFO -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]   Rendered dashboard/show.html.erb within layouts/application (1.5ms)
2022-06-21T12:54:08.893279+00:00 app[web.1]: I, [2022-06-21T12:54:08.893225 #9]  INFO -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13] Completed 500 Internal Server Error in 7ms (ActiveRecord: 1.1ms)
2022-06-21T12:54:08.894220+00:00 app[web.1]: F, [2022-06-21T12:54:08.894169 #9] FATAL -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]
2022-06-21T12:54:08.894271+00:00 app[web.1]: F, [2022-06-21T12:54:08.894239 #9] FATAL -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13] ActionView::Template::Error (The asset "chartkick.js" is not present in the asset pipeline.
2022-06-21T12:54:08.894272+00:00 app[web.1]: ):
2022-06-21T12:54:08.894439+00:00 app[web.1]: F, [2022-06-21T12:54:08.894403 #9] FATAL -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]     11:   <%= csrf_meta_tags %>
2022-06-21T12:54:08.894440+00:00 app[web.1]: [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]     12:   <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700' rel='stylesheet' type='text/css'>
2022-06-21T12:54:08.894441+00:00 app[web.1]: [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]     13:
2022-06-21T12:54:08.894441+00:00 app[web.1]: [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]     14:   <%= javascript_include_tag "//www.google.com/jsapi", "chartkick" %>
2022-06-21T12:54:08.894442+00:00 app[web.1]: [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]     15: </head>
2022-06-21T12:54:08.894442+00:00 app[web.1]: [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]     16: <body>
2022-06-21T12:54:08.894443+00:00 app[web.1]: [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]     17:   <div id='container'>
2022-06-21T12:54:08.894482+00:00 app[web.1]: F, [2022-06-21T12:54:08.894452 #9] FATAL -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13]
2022-06-21T12:54:08.894523+00:00 app[web.1]: F, [2022-06-21T12:54:08.894495 #9] FATAL -- : [dc5be6b7-715a-47a0-8936-e0ba1c6b2c13] app/views/layouts/application.html.erb:14:in `_app_views_layouts_application_html_erb___4496802780226790006_47054455194320'

dimanche 19 juin 2022

Edit and Update for assosiated model Rails

I tried to create edit and update action for my assosiated model named as Entity. But When edit pages pop up no saved data shown. Means it is showing all field as empty and when I put values in it, creates a another object. And also validation messages are not showing

Entities Controller

class EntitiesController < ApplicationController

  def index

  if params[:search]
    @schema =  Schema.find_by(id: params[:schema_id])
    @entities = @schema.entities.search(params[:search]).order("created_at DESC")
  elsif params[:schema_id]
    @schema =  Schema.find_by(id: params[:schema_id])
    @entities = @schema.entities
  else
    @schema =  Schema.find_by(id: params[:id])
    @entities = @schema.entities
  end
  # binding.pry
end

  def new
      @schema =  Schema.find(params[:schema_id])
      @entity = Entity.new
  end

  def create
    @schema =  Schema.find(params[:schema_id])
    @entity = @schema.entities.new(entity_params)
    if @entity.save
      redirect_to schema_entities_path(@schema)
    else
      redirect_to new_schema_entity_path(@schema)
    end
  end

  def edit
    p '6532646546575675676576575'
    p 'Entering into edit method'
      @schema = Schema.find(params[:schema_id])
      p @schema
      p '6532646546575675676576575'
      @entity = @schema.entities.find(params[:id])
      p @entity
        p '6532646546575675676576575'
  end
  def update
      @schema = Schema.find(params[:schema_id])
      @entity = @schema.entities.find(params[:id])

      if @entity.update(entity_params)
        redirect_to schema_entities_path(@schema)
      else
        render 'edit'
      end

  end

  def destroy
    @schema = Schema.find(params[:schema_id])
    @entity = @schema.entities.find(params[:id])
    @entity.destroy
    redirect_to schema_entities_path(@schema)
  end
  private

    def entity_params
       params.require(:entity).permit(:clientId, :name, :description, :mnemonic)
   end
end

edit form for it:

<%= form_for([@schema, @schema.entities.build], data: { turbo: false }) do |f| %>
      <%= f.text_field :clientId, placeholder:"ClientId" %>
      <%= f.text_area :name, placeholder: "Name" %>
      <%= f.text_area :description, placeholder: "Description" %>
      <%= f.text_area :mnemonic, placeholder: "Mnemonic" %>
      <%= f.submit 'Submit' %>


  <% if @entity.errors.any? %>
     <div id="error_explanation">
         <% @entity.errors.full_messages.each do |msg| %>
           <p class="error_msg"><%= msg %></p>
         <% end %>
     </div>
     <% end %>
<% end %>

Its model:

class Entity < ApplicationRecord
  belongs_to :schema
  has_many :fields, dependent: :destroy
  has_many :joins, through: :fields


  validates :name, presence: true, uniqueness: true

  def self.search(search)
    where("name LIKE ?", "%#{search}%")
  end
end

This is how I am passing values from index page:

<%= link_to 'Edit', edit_schema_entity_path(schema_id: @schema.id, id: data.id)  if data.id %>

samedi 18 juin 2022

How to fix error in rails 7 action view helper?

I'm getting this error ("wrong number of arguments (given 1, expected 0)") in the following helper.

module PropertiesHelper
        def property_thumbnail
          img = property.photo.present? ? property.photo.thumb.url : "placeholder.png"
          image_tag img, class: "property_thumb"
        end
end

jeudi 16 juin 2022

Ruby On Rails undefined local variable or method `profile_params' for ProfileController:Class

First time using stackoverflow. Also my english is pretty bad please do not blame me. I am a noob trying to learn RoR. I want to create a controller and a view to modify data/informations of a user. Like i want to change the phone number of a user but i do not know how. Below are some photos with my code.

error

routes

application_controller

app/controllers/profile_controller

app/views/profile/index.html

Is there a way to save the changes mage to local storage in ember.js

I have been trying to implement a cart function to my e-commerce . In this cart function when ever I add an item, if its already present in the cart we must increase the quantity. Everything works fine but whenever I refresh the browser or add a new item the values get reverted. How can I fix this.

My frontend is ember.js v3.4.4 and Backend Ruby on Rails v7.0.2.3

The addon I'm using for localstorage is ember-localstorage-addon

Below I have attached a snippet how I add elements to the cart

// app/service/shopping-cart.js

addItem(itemId){
    const itemArray = this.itemsIds.content;
    const index = itemArray.findIndex(object => object.id === itemId.id);
    const itemElement = itemArray[index];
    console.log(itemElement);
    if(itemElement){

        console.log(itemId);
        const quantityOfAddedElement = parseInt(itemId.quantity) + parseInt(itemElement.quantity);
        console.log(quantityOfAddedElement);
        const totalPrice = parseInt(itemId.price) + parseInt(itemElement.price);
        itemElement.quantity = quantityOfAddedElement;
        itemElement.price = totalPrice;
        console.log(quantityOfAddedElement);
    }
    else{
        this.get('itemsIds').addObject((itemId));
    }
}
// app/controller/product.js
actions:{
    addToItem(model){
        const id = model.id;
        const title = model.title;
        const quantity = this.quantity;
        const images = model.images;
        const price = quantity * model.price;
        const dbQuantity = model.quantity;

        this.shoppingCart.addItem({
            id,
            title, 
            price,
            quantity,
            images,
        });
    },
 }

dimanche 12 juin 2022

Associated in 3 table rails

I have to create 3rd table having assosisted with 2nd.

1st table: Schema
2nd table: Entity 
3rd table: Fields

Relation between them is:

Schema(id) ===>  Entity
Entity(id) ===> Fields

I have created table and views till Entity but don't know how to create table for field

Fields having values as:

"clientId"
"name"
"description"
"mnemonic"
"columnType"
"display"
"fallbackId"
"conceptDisplay"
"businessName"

Help me to create model and views for it to show all the fiels related to entity:

I tried something like this:

entity.rb => model

class Entity < ApplicationRecord
  belongs_to :schema
  has_many :fields, dependent: :destroy
end

field.rb => model

class Field < ApplicationRecord
  belongs_to :entity
  belongs_to :schema
end

schema.rb => model

class Schema < ApplicationRecord
  has_many :entities, dependent: :destroy

  validates :name, presence: true, uniqueness: true
  validates :schemaId, presence: true, uniqueness: true
end

controller for field:

class FieldsController < ApplicationController
  def index
    @schema =  Schema.find(params[:id])
    @entity =  @schema.entities.find_by(id: params[:id])
    @fields =  @entity.fields
  end
end

views for entity where i have to create link_to to show all field for that entity

<div class="content">
  <ul>
  <% @entities.each do |data| %>
    <li>
      <%= data.clientId %>
      <%= link_to data.name, fields_index_path(id: data.id) %>
      <%= data.description %>
      <%= data.mnemonic %>
    </li>

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

samedi 11 juin 2022

Rails thinks my pc is a touch screen tablet

Every navbar I render in my rails server using Bulma or Bootstrap the navbar items dont display or get squished to the left side of my screen. Only the Bulma logo & the navbar burger on the right render properly, that in the documentation it says it should only displays on mobile devices. While "home,

I think rails thinks my pc is a touch screen tablet.

application.html.erb

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Hello AlphaBlog!</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
      </head>
      <body>
        
      
        
    <nav class="navbar" role="navigation" aria-label="main navigation">
      <div class="navbar-brand">
        <a class="navbar-item" href="https://bulma.io">
          <img src="https://bulma.io/images/bulma-logo.png" width="112" height="28">
        </a>

        <a role="button" class="navbar-menu" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample">
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
        </a>
      </div>

      <div id="navbarBasicExample" class="navbar-brand">
        <div class="navbar-start">
          <a class="navbar-item">
            Home
          </a>

          <a class="navbar-item">
            Documentation
          </a>

          <div class="navbar-item has-dropdown is-hoverable">
            <a class="navbar-link">
              More
            </a>

            <div class="navbar-dropdown">
              <a class="navbar-item">
                About
              </a>
              <a class="navbar-item">
                Jobs
              </a>
              <a class="navbar-item">
                Contact
              </a>
              <hr class="navbar-divider">
              <a class="navbar-item">
                Report an issue
              </a>
            </div>
          </div>
        </div>

        <div class="navbar-end">
          <div class="navbar-item">
            <div class="buttons">
              <a class="button is-primary">
                <strong>Sign up</strong>
              </a>
              <a class="button is-light">
                Log in
              </a>
            </div>
          </div>
        </div>
      </div>
    </nav>
  <section class="section">
    <div class="container">
      <h1 class="title">
        Hello World
      </h1>
      <p class="subtitle">
        My first website with <strong>Bulma</strong>!
      </p>
    </div>
<% flash.each do |name,msg| %>
          <%=msg%>
        <%end%>
        <%= yield %>
      </body>

useful info?: I used to own a drawing tablet that I think may have caused this issue when I installed all the software I just no idea where to look. If I can somehow make rails only display desktop versions of the app I think i can work around this issue while i still have this computer.

form_for NoMethodError in Entities#new

Tried to create a form for assosiated model in rails but form_for giving error " NoMethodError in Entities#new " " undefined method `entities' for nil:NilClass"

Code for model

<!--Schema model -->

class Schema < ApplicationRecord
  has_many :entities, dependent: :destroy

  validates :name, presence: true, uniqueness: true
  validates :schemaId, presence: true, uniqueness: true
end

<!--Entity Model -->

class Entity < ApplicationRecord
  belongs_to :schema
end

<!-- Entity Controller -->
class EntitiesController < ApplicationController

  def index
    @schema = Schema.find_by(:id => params[:id])
    @entities = @schema.entities
  end


  def new
      @schema = Schema.find_by(:id => params[:id])
      @entity = Entity.new
  end

  def create
    @schema = Schema.find_by(:id => params[:id])
    @entity = @schema.entities.new(entity_params)
    @entity.save!
  end

  private

    def entity_params
       params.require(:entity).permit(:clientId, :name, :description, :mnemonic)
   end
end



<!-- Entity_new_form-->
<%= form_for [@schema, @schema.entities.build] do |f| %>
  <p>
    <%= f.label :clientId %><br/>
    <%= f.text_field :clientId %>
  </p>
  <p>
    <%= f.label :name %><br/>
    <%= f.text_area :name %>
  </p>

  <p>
    <%= f.label :description %><br/>
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.label :mnemonic %><br/>
    <%= f.text_area :mnemonic %>
  </p>
  <p>
    <%= f.submit 'Submit' %>
  </p>
<% end %>

This is giving error here entity is associated with Schema... I have to take input from user for new entity but this form is giving me error.

vendredi 10 juin 2022

Ruby - IF or OR condition on a JOINS statement

How can I specify a OR condition on a joins statement? Basically I don't want the joins for where(:tenant_id => User.current_tenant. If I try OR condition I get the following error.

I get the following error.

Relation passed to #or must be structurally compatible. Incompatible values: [:joins] [catalog/explorer]

  scope :public_service_templates,                  ->         { joins(:miq_user_roles).where(miq_user_roles: { settings: nil}).or(where(:tenant_id => User.current_tenant)) }

jeudi 9 juin 2022

Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL

I am using a legacy version of rails 3.2.22 and while trying to execute my migration file, I encountered this error:

rake db:migrate
==  CreateBooks: migrating ====================================================
-- create_table(:books)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead: CREATE TABLE `books` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `Book Title` varchar(255), `Author` varchar(255), `Date Published` date, `Book ID` int(11), `Checked Out?` tinyint(1), `Return Time` datetime, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:245:in `block in execute'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `block in log'
/usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:245:in `execute'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/mysql2_adapter.rb:213:in `execute'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/schema_statements.rb:170:in `create_table'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:434:in `create_table'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:466:in `block in method_missing'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:438:in `block in say_with_time'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:438:in `say_with_time'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:458:in `method_missing'
/home/elliot/Desktop/SAIT WORK/Library/db/migrate/20220609183208_create_books.rb:3:in `up'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:410:in `block (2 levels) in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:410:in `block in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:129:in `with_connection'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:389:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:528:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:720:in `block (2 levels) in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:777:in `call'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:777:in `ddl_transaction'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:719:in `block in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:700:in `each'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:700:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:570:in `up'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:551:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/railties/databases.rake:193:in `block (2 levels) in <top (required)>'
/usr/share/rvm/gems/ruby-2.1.10/gems/rake-12.3.3/exe/rake:27:in `<top (required)>'
/usr/share/rvm/gems/ruby-2.1.10/bin/ruby_executable_hooks:24:in `eval'
/usr/share/rvm/gems/ruby-2.1.10/bin/ruby_executable_hooks:24:in `<main>'

I am well aware of the fact that people have posted this problem in the past and there have been solutions posted that helped solve this problem but when I attempt to utilize those solutions, I encounter errors. In particular, I am referencing this guide: Link to solution 1

However, when I implement the suggested changes, I can run the rake db:migrate, however, when I try to run any other rails command (i.e. rails s or rails console), I get this error:

rails s
=> Booting WEBrick
=> Rails 3.2.22 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- /home/elliot/Desktop/SAIT WORK/Library/lib/patches/abstract_mysql_adapter (LoadError)
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `block in require'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require'
    from /home/elliot/Desktop/SAIT WORK/Library/config/environment.rb:3:in `<top (required)>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `block in require'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require'
    from /home/elliot/Desktop/SAIT WORK/Library/config.ru:3:in `block in <main>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:51:in `instance_eval'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:51:in `initialize'
    from /home/elliot/Desktop/SAIT WORK/Library/config.ru:in `new'
    from /home/elliot/Desktop/SAIT WORK/Library/config.ru:in `<main>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:40:in `eval'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:40:in `parse_file'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/server.rb:200:in `app'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands/server.rb:46:in `app'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/server.rb:304:in `wrapped_app'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/server.rb:254:in `start'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands/server.rb:70:in `start'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands.rb:55:in `block in <top (required)>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands.rb:50:in `tap'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

I have also tried the implementing the solution suggested here: Link to Solution 2 but I would run into the same error. Could this problem relate to the naming convention of my models and tables? I am very stuck so any help would be greatly appreciated.

app/models/book.rb

class Book < ActiveRecord::Base
  # attr_accessible :title, :body
end

config/database.yml !!!Note that I omitted the password and username for privacy, but they are implemented correctly I believe!!!

# MySQL.  Versions 4.1 and 5.0 are recommended.
# 
# Install the MYSQL driver
#   gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
#   gem 'mysql2'
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: Library_development
  pool: 5
  username: **
  password: **
  socket: /var/run/mysqld/mysqld.sock

# 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:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: Library_test
  pool: 5
  username: **
  password: **
  socket: /var/run/mysqld/mysqld.sock

production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: Library_production
  pool: 5
  username: **
  password: **
  socket: /var/run/mysqld/mysqld.sock

db/migrate/20220609183208_create_books.rb

class CreateBooks < ActiveRecord::Migration
  def up
    create_table :books do |t|
      t.string 'Book Title'
      t.string 'Author'
      t.date "Date Published"
      t.integer "Book ID"
      t.boolean "Checked Out?"
      t.datetime "Return Time"
      t.timestamps
    end
  end

  def down
    drop_table :books
  end

end

Gemfile

source 'https://rubygems.org'

gem 'rails', '3.2.22'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

# gem 'mysql2'

gem 'mysql'
gem 'mysql2', "~> 0.3.10"

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
# gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'debugger'

gem 'devise'

gem 'cancancan'

gem 'mail_interceptor', group: [:development, :staging]

#gem 'sidekiq', '~>6.0.0'

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
  gem 'rspec-rails', '~> 3.5'
  gem 'factory_bot_rails'
  gem 'database_cleaner'
end

gem "bootstrap-sass", "~> 3.1.1.0"

mercredi 8 juin 2022

Ruby - Convert SQL unnest to Arel

How can I convert the following query into Arel? I want to define a where condition using arel.

select * from tenants where id in (select a.id::int from tenants t2 cross join unnest(string_to_array(t2.ancestry, '/')) as a(id) where t2.id = 39);

Here is how the table output looks like:

-[ RECORD 1 ]-------------+------------------
id                        | 39
domain                    |
subdomain                 |
name                      | Child_Teanant_201
login_text                |
logo_file_name            |
logo_content_type         |
logo_file_size            |
logo_updated_at           |
login_logo_file_name      |
login_logo_content_type   |
login_logo_file_size      |
login_logo_updated_at     |
ancestry                  | 1/35
divisible                 | t
description               | Child_Teanant_201
use_config_for_attributes | f
default_miq_group_id      | 51
source_type               |
source_id                 |

Ruby - Has_many through returns syntax error

When I try the following code

  has_many: users, through: :miq_groups, :foreign_key => :current_group_id, :primary_key => :miq_group_id;

I get RipperRubyParser::SyntaxError: syntax error, unexpected ':', expecting 'end' error.

  has_many :miq_groups, :foreign_key => :id, :primary_key => :miq_group_id;
  has_many :entitlements, through: :miq_groups; 
  has_many :miq_user_roles, through: :entitlements;

  has_many: users, through: :miq_groups, :foreign_key => :current_group_id, :primary_key => :miq_group_id;

Users table has current_group_id and miq_groups table has miq_group_id and both are foreign_key not primary.

Any idea how to resolve the error? I was just to include has_many: users.

Ruby - Query with multiple subqueries

How can I write a where condition query using ruby for the following SQL statement? I believe we need to define a belongs_to on the service_tempaltes model before we can query other tables?

select * from service_templates where miq_group_id IN ( SELECT miq_group_id from entitlements where miq_user_role_id IN (SELECT id from miq_user_roles where settings is NULL) );

service_templates by default cannot join with other tables unless we define a belongs_to which I'm not sure if necessary. But I want to write a where condition in the scope section based on the above query.

scope :public_service_templates,                  ->         { where(miq_user_roles: { settings: nil }) }

Model definition of entitlements:

class Entitlement < ApplicationRecord
  belongs_to :miq_group
  belongs_to :miq_user_role
  ...
end

Model definition of miq_user_roles.

class MiqUserRole < ApplicationRecord
  DEFAULT_TENANT_ROLE_NAME = "EvmRole-tenant_administrator"

  has_many                :entitlements, :dependent => :restrict_with_exception
  has_many                :miq_groups, :through => :entitlements
  has_and_belongs_to_many :miq_product_features, :join_table => :miq_roles_features
  ...
end

Model definition of miq_groups:

class MiqGroup < ApplicationRecord
  USER_GROUP   = "user"
  SYSTEM_GROUP = "system"
  TENANT_GROUP = "tenant"

  belongs_to :tenant
  has_one    :entitlement, :dependent => :destroy, :autosave => true
  has_one    :miq_user_role, :through => :entitlement
  has_and_belongs_to_many :users
  has_many   :vms,         :dependent => :nullify
  has_many   :miq_templates, :dependent => :nullify
  has_many   :miq_reports, :dependent => :nullify
  has_many   :miq_report_results, :dependent => :nullify
  has_many   :miq_widget_contents, :dependent => :destroy
  has_many   :miq_widget_sets, :as => :owner, :dependent => :destroy
  has_many   :miq_product_features, :through => :miq_user_role
  has_many   :authentications, :dependent => :nullify
  ...
end

Model definition of service_templates.

class ServiceTemplate < ApplicationRecord
  include SupportsFeatureMixin

  DEFAULT_PROCESS_DELAY_BETWEEN_GROUPS = 120

  GENERIC_ITEM_SUBTYPES = {
    "custom"          => N_("Custom"),
    "vm"              => N_("Virtual Machine"),
    "playbook"        => N_("Playbook"),
    "hosted_database" => N_("Hosted Database"),
    "load_balancer"   => N_("Load Balancer"),
    "storage"         => N_("Storage")
  }.freeze

  SERVICE_TYPE_ATOMIC    = 'atomic'.freeze
  SERVICE_TYPE_COMPOSITE = 'composite'.freeze

  RESOURCE_ACTION_UPDATE_ATTRS = [:dialog,
                                  :dialog_id,
                                  :fqname,
                                  :configuration_template,
                                  :configuration_template_id,
                                  :configuration_template_type].freeze

  include CustomActionsMixin
  include ServiceMixin
  include OwnershipMixin
  include NewWithTypeStiMixin
  include TenancyMixin
  include ArchivedMixin
  include CiFeatureMixin
  include_concern 'Filter'
  include_concern 'Copy'


  validates :name, :presence => true
  belongs_to :tenant

  has_many   :service_templates, :through => :service_resources, :source => :resource, :source_type => 'ServiceTemplate'
  has_many   :services


  has_many :service_template_tenants, :dependent => :destroy
  has_many :additional_tenants, :through => :service_template_tenants, :source => :tenant, :dependent => :destroy

  has_one :picture, :dependent => :destroy, :as => :resource, :autosave => true

  belongs_to :service_template_catalog
  belongs_to :zone
  belongs_to :currency, :inverse_of => false

  has_many   :dialogs, -> { distinct }, :through => :resource_actions
  has_many   :miq_schedules, :as => :resource, :dependent => :destroy

  has_many   :miq_requests, :as => :source, :dependent => :nullify
  has_many   :active_requests, -> { where(:request_state => MiqRequest::ACTIVE_STATES) }, :as => :source, :class_name => "MiqRequest"

  virtual_column   :type_display,                 :type => :string
  virtual_column   :template_valid,               :type => :boolean
  virtual_column   :template_valid_error_message, :type => :string
  virtual_column   :archived,                     :type => :boolean
  virtual_column   :active,                       :type => :boolean

  default_value_for :internal, false
  default_value_for :service_type, SERVICE_TYPE_ATOMIC
  default_value_for(:generic_subtype) { |st| 'custom' if st.prov_type == 'generic' }

  virtual_has_one :config_info, :class_name => "Hash"

  scope :with_service_template_catalog_id,          ->(cat_id) { where(:service_template_catalog_id => cat_id) }
  scope :without_service_template_catalog_id,       ->         { where(:service_template_catalog_id => nil) }
  scope :with_existent_service_template_catalog_id, ->         { where.not(:service_template_catalog_id => nil) }
  scope :displayed,                                 ->         { where(:display => true) }
  scope :public_service_templates,                  ->         { where(:display => true) }


  supports :order do
    unsupported_reason_add(:order, 'Service template does not belong to a service catalog') unless service_template_catalog
    unsupported_reason_add(:order, 'Service template is not configured to be displayed') unless display
  end
  alias orderable?     supports_order?
  alias validate_order supports_order?


  def self.with_tenant(tenant_id)
    tenant = Tenant.find(tenant_id)
    where(:tenant_id => tenant.ancestor_ids + [tenant_id])\
  end

rails server not response after idle a while(1 or 2 hours)

I started rails server with puma webserver.(Centos 7) simple command rails s -b 0.0.0.0 . It is working great in working hours these day. But next day can't call rails server.(but can call rails server 1 times and like cache . And then no more access.) It seen like request to server and don't get response and waiting server response. After check rails log, only have one update log for today. (when I get response 1st time.)

mardi 7 juin 2022

How can I check whether or not a data-testid exists on my page using Ruby?

How can I check whether or not a data-testid exists on my page using Ruby ? I ask this because I see that there are some ways to search for selectors, but I don't know exactly if this is the correct way or not. I'm trying to do it like this

expect(page).should have_no_selector("[data-testid='prepay-enroll-now-button']");



expect(page).should have_selector("[data-testid='prepay-enroll-now-button']");

lundi 6 juin 2022

Can't join 'ServiceTemplate' to association named 'miq_user_roles'; perhaps you misspelled it?

Why can't I join miq_user_roles with ServiceTemplate? ServiceTemplate has a column miq_group_id which is the id of miq_user_roles.

  scope :public_service_templates,                  ->         { joins(:miq_user_roles).where(miq_user_roles: { settings: nil }) }

When I try the above code I get the following error:

Can't join 'ServiceTemplate' to association named 'miq_user_roles'; perhaps you misspelled it?

Following is the actual model definition where I want to include miq_user_roles table.

class ServiceTemplate < ApplicationRecord
  include SupportsFeatureMixin

  DEFAULT_PROCESS_DELAY_BETWEEN_GROUPS = 120

  GENERIC_ITEM_SUBTYPES = {
    "custom"          => N_("Custom"),
    "vm"              => N_("Virtual Machine"),
    "playbook"        => N_("Playbook"),
    "hosted_database" => N_("Hosted Database"),
    "load_balancer"   => N_("Load Balancer"),
    "storage"         => N_("Storage")
  }.freeze

  SERVICE_TYPE_ATOMIC    = 'atomic'.freeze
  SERVICE_TYPE_COMPOSITE = 'composite'.freeze

  RESOURCE_ACTION_UPDATE_ATTRS = [:dialog,
                                  :dialog_id,
                                  :fqname,
                                  :configuration_template,
                                  :configuration_template_id,
                                  :configuration_template_type].freeze

  include CustomActionsMixin
  include ServiceMixin
  include OwnershipMixin
  include NewWithTypeStiMixin
  include TenancyMixin
  include ArchivedMixin
  include CiFeatureMixin
  include_concern 'Filter'
  include_concern 'Copy'


  validates :name, :presence => true
  belongs_to :tenant

  has_many   :service_templates, :through => :service_resources, :source => :resource, :source_type => 'ServiceTemplate'
  has_many   :services


  has_many :service_template_tenants, :dependent => :destroy
  has_many :additional_tenants, :through => :service_template_tenants, :source => :tenant, :dependent => :destroy

  has_one :picture, :dependent => :destroy, :as => :resource, :autosave => true

  belongs_to :service_template_catalog
  belongs_to :zone
  belongs_to :currency, :inverse_of => false

  has_many   :dialogs, -> { distinct }, :through => :resource_actions
  has_many   :miq_schedules, :as => :resource, :dependent => :destroy

  has_many   :miq_requests, :as => :source, :dependent => :nullify
  has_many   :active_requests, -> { where(:request_state => MiqRequest::ACTIVE_STATES) }, :as => :source, :class_name => "MiqRequest"

  virtual_column   :type_display,                 :type => :string
  virtual_column   :template_valid,               :type => :boolean
  virtual_column   :template_valid_error_message, :type => :string
  virtual_column   :archived,                     :type => :boolean
  virtual_column   :active,                       :type => :boolean

  default_value_for :internal, false
  default_value_for :service_type, SERVICE_TYPE_ATOMIC
  default_value_for(:generic_subtype) { |st| 'custom' if st.prov_type == 'generic' }

  virtual_has_one :config_info, :class_name => "Hash"

  scope :with_service_template_catalog_id,          ->(cat_id) { where(:service_template_catalog_id => cat_id) }
  scope :without_service_template_catalog_id,       ->         { where(:service_template_catalog_id => nil) }
  scope :with_existent_service_template_catalog_id, ->         { where.not(:service_template_catalog_id => nil) }
  scope :displayed,                                 ->         { where(:display => true) }
  scope :public_service_templates,                  ->         { joins(:miq_user_roles).where(miq_user_roles: { settings: nil }) }


  supports :order do
    unsupported_reason_add(:order, 'Service template does not belong to a service catalog') unless service_template_catalog
    unsupported_reason_add(:order, 'Service template is not configured to be displayed') unless display
  end
  alias orderable?     supports_order?
  alias validate_order supports_order?


  def self.with_tenant(tenant_id)
    tenant = Tenant.find(tenant_id)
    where(:tenant_id => tenant.ancestor_ids + [tenant_id])\
  end

There is an issue connecting to your database with your username/password, username:

Postgresql ActiveRecord::DatabaseConnectionError

There is an issue connecting to your database with your username/password, username: sanad. Please check your database configuration to ensure the username/password are valid.

PG::ConnectionBad: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "user"

Here is the database code

dimanche 5 juin 2022

Ruby - PG::UndefinedTable: ERROR: missing FROM-clause entry for table

I'm getting the following error when I'm trying to query another table in a model definition.

PG::UndefinedTable: ERROR: missing FROM-clause entry for table "miq_user_roles" LINE 1: ..." = $1 AND "service_templates"."display" = $2 AND "miq_user_... ^ [catalog/explorer]

Any idea how to resolve this?

  scope :with_service_template_catalog_id,          ->(cat_id) { where(:service_template_catalog_id => cat_id) }
  scope :without_service_template_catalog_id,       ->         { where(:service_template_catalog_id => nil) }
  scope :with_existent_service_template_catalog_id, ->         { where.not(:service_template_catalog_id => nil) }
  scope :displayed,                                 ->         { where(:display => true) }
  scope :public_service_templates,                  ->         { where("miq_user_roles.settings" => nil) }

Here is the full code:

class ServiceTemplate < ApplicationRecord
  include SupportsFeatureMixin

  DEFAULT_PROCESS_DELAY_BETWEEN_GROUPS = 120

  GENERIC_ITEM_SUBTYPES = {
    "custom"          => N_("Custom"),
    "vm"              => N_("Virtual Machine"),
    "playbook"        => N_("Playbook"),
    "hosted_database" => N_("Hosted Database"),
    "load_balancer"   => N_("Load Balancer"),
    "storage"         => N_("Storage")
  }.freeze

  SERVICE_TYPE_ATOMIC    = 'atomic'.freeze
  SERVICE_TYPE_COMPOSITE = 'composite'.freeze

  RESOURCE_ACTION_UPDATE_ATTRS = [:dialog,
                                  :dialog_id,
                                  :fqname,
                                  :configuration_template,
                                  :configuration_template_id,
                                  :configuration_template_type].freeze

  include CustomActionsMixin
  include ServiceMixin
  include OwnershipMixin
  include NewWithTypeStiMixin
  include TenancyMixin
  include ArchivedMixin
  include CiFeatureMixin
  include_concern 'Filter'
  include_concern 'Copy'

  validates :name, :presence => true
  belongs_to :tenant

  has_many   :service_templates, :through => :service_resources, :source => :resource, :source_type => 'ServiceTemplate'
  has_many   :services

  has_many :service_template_tenants, :dependent => :destroy
  has_many :additional_tenants, :through => :service_template_tenants, :source => :tenant, :dependent => :destroy

  has_one :picture, :dependent => :destroy, :as => :resource, :autosave => true

  belongs_to :service_template_catalog
  belongs_to :zone
  belongs_to :currency, :inverse_of => false

  has_many   :dialogs, -> { distinct }, :through => :resource_actions
  has_many   :miq_schedules, :as => :resource, :dependent => :destroy

  has_many   :miq_requests, :as => :source, :dependent => :nullify
  has_many   :active_requests, -> { where(:request_state => MiqRequest::ACTIVE_STATES) }, :as => :source, :class_name => "MiqRequest"

  virtual_column   :type_display,                 :type => :string
  virtual_column   :template_valid,               :type => :boolean
  virtual_column   :template_valid_error_message, :type => :string
  virtual_column   :archived,                     :type => :boolean
  virtual_column   :active,                       :type => :boolean

  default_value_for :internal, false
  default_value_for :service_type, SERVICE_TYPE_ATOMIC
  default_value_for(:generic_subtype) { |st| 'custom' if st.prov_type == 'generic' }

  virtual_has_one :config_info, :class_name => "Hash"


  scope :with_service_template_catalog_id,          ->(cat_id) { where(:service_template_catalog_id => cat_id) }
  scope :without_service_template_catalog_id,       ->         { where(:service_template_catalog_id => nil) }
  scope :with_existent_service_template_catalog_id, ->         { where.not(:service_template_catalog_id => nil) }
  scope :displayed,                                 ->         { where(:display => true) }
  scope :public_service_templates,                  ->         { where("miq_user_roles.settings" => nil) }

Ruby - Query another table in a model definition

I want to query another table in a model definition. For instance, I have a table called miq_user_roles and I want to query and retrievesettings column value.

I tried adding the following

has_many   :miq_user_roles

but when I try the where condition where(:settings => nil)

I get the error service_template doesn't have settings column. How can I query miq_user_roles for settings instead of service_template

service_template has a column called miq_group_id and its the id of miq_user_rolestable.

Following is the actual model definition where I want to include miq_user_roles table.

class ServiceTemplate < ApplicationRecord
  include SupportsFeatureMixin

  DEFAULT_PROCESS_DELAY_BETWEEN_GROUPS = 120

  GENERIC_ITEM_SUBTYPES = {
    "custom"          => N_("Custom"),
    "vm"              => N_("Virtual Machine"),
    "playbook"        => N_("Playbook"),
    "hosted_database" => N_("Hosted Database"),
    "load_balancer"   => N_("Load Balancer"),
    "storage"         => N_("Storage")
  }.freeze

  SERVICE_TYPE_ATOMIC    = 'atomic'.freeze
  SERVICE_TYPE_COMPOSITE = 'composite'.freeze

  RESOURCE_ACTION_UPDATE_ATTRS = [:dialog,
                                  :dialog_id,
                                  :fqname,
                                  :configuration_template,
                                  :configuration_template_id,
                                  :configuration_template_type].freeze

  include CustomActionsMixin
  include ServiceMixin
  include OwnershipMixin
  include NewWithTypeStiMixin
  include TenancyMixin
  include ArchivedMixin
  include CiFeatureMixin
  include_concern 'Filter'
  include_concern 'Copy'


  validates :name, :presence => true
  belongs_to :tenant

  has_many   :service_templates, :through => :service_resources, :source => :resource, :source_type => 'ServiceTemplate'
  has_many   :services


  has_many :service_template_tenants, :dependent => :destroy
  has_many :additional_tenants, :through => :service_template_tenants, :source => :tenant, :dependent => :destroy

  has_one :picture, :dependent => :destroy, :as => :resource, :autosave => true

  belongs_to :service_template_catalog
  belongs_to :zone
  belongs_to :currency, :inverse_of => false

  has_many   :dialogs, -> { distinct }, :through => :resource_actions
  has_many   :miq_schedules, :as => :resource, :dependent => :destroy

  has_many   :miq_requests, :as => :source, :dependent => :nullify
  has_many   :active_requests, -> { where(:request_state => MiqRequest::ACTIVE_STATES) }, :as => :source, :class_name => "MiqRequest"

  virtual_column   :type_display,                 :type => :string
  virtual_column   :template_valid,               :type => :boolean
  virtual_column   :template_valid_error_message, :type => :string
  virtual_column   :archived,                     :type => :boolean
  virtual_column   :active,                       :type => :boolean

  default_value_for :internal, false
  default_value_for :service_type, SERVICE_TYPE_ATOMIC
  default_value_for(:generic_subtype) { |st| 'custom' if st.prov_type == 'generic' }

  virtual_has_one :config_info, :class_name => "Hash"

  scope :with_service_template_catalog_id,          ->(cat_id) { where(:service_template_catalog_id => cat_id) }
  scope :without_service_template_catalog_id,       ->         { where(:service_template_catalog_id => nil) }
  scope :with_existent_service_template_catalog_id, ->         { where.not(:service_template_catalog_id => nil) }
  scope :displayed,                                 ->         { where(:display => true) }
  scope :public_service_templates,                  ->         { where(:display => true) }


  supports :order do
    unsupported_reason_add(:order, 'Service template does not belong to a service catalog') unless service_template_catalog
    unsupported_reason_add(:order, 'Service template is not configured to be displayed') unless display
  end
  alias orderable?     supports_order?
  alias validate_order supports_order?


  def self.with_tenant(tenant_id)
    tenant = Tenant.find(tenant_id)
    where(:tenant_id => tenant.ancestor_ids + [tenant_id])\
  end

Debug_inspector extension was not loaded rake aborted

I try install Canvas LMS on ubuntu 20.4 And I get the error when executing this command

commands:

sysadmin@appserver:var/canvas$ sudo yarn install sysadmin@appserver:/var/canvas$ sudo RAILS_ENV=production bundle exec rake canvas:compile_assets

Result:

debug_inspector extension was not loaded rake aborted! LoadError: incompatible library version - /var/canvas/vendor/bundle/ruby/2.7.0/gems/io-console-0.5.11/lib/io/console.so /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:324:in require' /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:324:in block in require' /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:291:in load_dependency' /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:324:in require' /var/canvas/vendor/bundle/ruby/2.7.0/gems/reline-0.3.1/lib/reline.rb:1:in <top (required)>' /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:324:in require' /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:324:in block in require' /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:291:in load_dependency' /var/canvas/vendor/bundle/ruby/2.7.0/gems/activesupport-6.0.4.7/lib/active_support/dependencies.rb:324:in require' /var/canvas/vendor/bundle/ruby/2.7.0/gems/irb-1.4.1/lib/irb.rb:13:in <top (required)>' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/runtime.rb:66:in require' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/runtime.rb:66:in block (2 levels) in require' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/runtime.rb:61:in each' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/runtime.rb:61:in block in require' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/runtime.rb:50:in each' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/runtime.rb:50:in require' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler.rb:174:in require' /var/canvas/config/application.rb:28:in <top (required)>' /var/canvas/Rakefile:6:in require' /var/canvas/Rakefile:6:in <top (required)>' /var/canvas/vendor/bundle/ruby/2.7.0/gems/rake-13.0.3/exe/rake:27:in <top (required)>' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/cli/exec.rb:63:in load' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/cli/exec.rb:63:in kernel_load' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/cli/exec.rb:28:in run' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/cli.rb:474:in exec' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/vendor/thor/lib/thor/command.rb:27:in run' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/vendor/thor/lib/thor/invocation.rb:127:in invoke_command' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/vendor/thor/lib/thor.rb:392:in dispatch' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/cli.rb:30:in dispatch' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/vendor/thor/lib/thor/base.rb:485:in start' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/cli.rb:24:in start' /var/lib/gems/2.7.0/gems/bundler-2.2.19/exe/bundle:49:in block in <top (required)>' /var/lib/gems/2.7.0/gems/bundler-2.2.19/lib/bundler/friendly_errors.rb:130:in with_friendly_errors' /var/lib/gems/2.7.0/gems/bundler-2.2.19/exe/bundle:37:in <top (required)>' /usr/local/bin/bundle:23:in load' /usr/local/bin/bundle:23:in ' (See full trace by running task with --trace)

ruby version : 2.7.5 gem: 3.1.6

Could not find gem 'pg x64-mingw32' in locally installed gems

Please help me get rid of this error

I am running Ruby on Rails on Windows 10

Could not find gem 'pg x64-mingw32' in locally installed gems.enter image description here

Removing double quotes from the beging and end of an array in Ruby

I have an array stored in a file, when I read this file to variable in Ruby it returns double quotes at the beginning and end of the array. I use Ruby 2.7.0

irb
irb(main):065:0> ports = IO.read('/ports_values')
irb(main):066:0> ports
=> "['127.0.0.1:6601:6601', '127.0.0.1:8000:8000', '127.0.0.1:7200:7200', '127.0.0.1:9201:9201', '5606:5606', '6304:6504', '6305:6505']"

But what I need this:

irb(main):066:0> ports
    => ['127.0.0.1:6601:6601', '127.0.0.1:8000:8000', '127.0.0.1:7200:7200', '127.0.0.1:9201:9201', '5606:5606', '6304:6504', '6305:6505']

without double quotes and I tried this ,but it did not work

irb(main):067:0> ports.gsub /"/, ' '
=> "['127.0.0.1:6601:6601', '127.0.0.1:8000:8000', '127.0.0.1:7200:7200', '127.0.0.1:9201:9201', '5606:5606', '6304:6504', '6305:6505']"

jeudi 2 juin 2022

How can I import a file csv into the Rails database? [closed]

I want to be able to import a file csv to my database, could someone help me on how to do it? When importing the csv file I want it to be registered in my database. my db:

  class CreateData < ActiveRecord::Migration[5.2]
  def change
    create_table :data do |t|
      t.string :radio
      t.integer :net
      t.integer :mcc
      t.integer :area
      t.integer :cell
      t.float :latitude 
      t.float :length
      t.integer :range
      t.integer :samples
      t.integer :changeble
      t.timestamps
    end
  end
end

How do I separate the Mobile app user and web app user in REST API?

There are different user like Coach, Athlete, Meet Director and Admin. Coach & Athlete are mobile app users, Admin are Web app user, Meet Director are both mobile & web app user. Please suggest any gem or share your thoughts.