jeudi 28 juillet 2022

Rails, table style issue

enter image description here

I am learning a rails on YouTube and here I am having issues with table style. The video is old and rails are update already. However, I am following exactly what he is doing in the video, but I ended up with this weird looking table of friends list.

I want to put all friends info next to each other up-and-down like the video.

mercredi 27 juillet 2022

Ruby on Rails: No such file or directory - bs_fetch:open_current_file:open (Errno::ENOENT)

Have a problem during creating a file:

"Traceback (most recent call last): 16: from bin/rails:4:in <main>' 15: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/bootsnap-1.12.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in require' 14: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/bootsnap-1.12.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in require' 13: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/railties-7.0.3.1/lib/rails/commands.rb:18:in ' 12: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/railties-7.0.3.1/lib/rails/command.rb:48:in invoke' 11: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/railties-7.0.3.1/lib/rails/command/base.rb:87:in perform' 10: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/thor-1.2.1/lib/thor.rb:392:in dispatch' 9: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/thor-1.2.1/lib/thor/invocation.rb:127:in invoke_command' 8: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/thor-1.2.1/lib/thor/command.rb:27:in run' 7: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/railties-7.0.3.1/lib/rails/commands/server/server_command.rb:134:in perform' 6: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/railties-7.0.3.1/lib/rails/commands/server/server_command.rb:134:in tap' 5: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/railties-7.0.3.1/lib/rails/commands/server/server_command.rb:137:in block in perform' 4: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/bootsnap-1.12.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in require' 3: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/bootsnap-1.12.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in require' 2: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/bootsnap-1.12.0/lib/bootsnap/compile_cache/iseq.rb:85:in load_iseq' 1: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/bootsnap-1.12.0/lib/bootsnap/compile_cache/iseq.rb:60:in fetch' C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/bootsnap-1.12.0/lib/bootsnap/compile_cache/iseq.rb:60:in `fetch': No such file or directory - bs_fetch:open_current_file:open (Errno::ENOENT)"

Please, help me with this issue :)

mardi 26 juillet 2022

wrong number of arguments when only one argument

I have this simple ruby code

Rails.logger.debug("callback local controller debug: #{auth_result.inspect} session= #{auth_result[:session]} ")
has_payment = check_billing(auth_result[:session])

The error raised is:

wrong number of arguments (given 2, expected 0..1)

But debug shows the auth_result[:session] is only one

callback local controller debug: {:session=>#<ShopifyAPI::Auth::Session:0x00007fcfc9099c78 @id="offline_something.myshopify.com", @shop="something.myshopify.com", @state=nil, @access_token="shpua_88da86ccdf7c482d1b102cff18f950e3", @scope=#<ShopifyAPI::Auth::AuthScopes:0x00007fcfc9099b88 @compressed_scopes=#<Set: {"write_themes", "write_script_tags", "write_content", "read_products", "write_files"}>, @expanded_scopes=#<Set: {"write_themes", "write_script_tags", "write_content", "read_products", "write_files", "read_themes", "read_script_tags", "read_content", "read_files"}>>, @associated_user_scope=nil, @expires=nil, @associated_user=nil, @is_online=false, @shopify_session_id=nil>, :cookie=><ShopifyAPI::Auth::Oauth::SessionCookie expires=2022-07-26 09:49:03.094180975 UTC, name="shopify_app_session", value="">} session= #<ShopifyAPI::Auth::Session:0x00007fcfc9099c78>

lundi 25 juillet 2022

if overriding filename method in carrierwave fog_google, upload file is not working

In my uploader, if I am overriding the filename method present in Store.rb library of carrierwave, then upload functionality is not working. It is showing code executed properly but file was not uploaded on GCS bucket.
Below is the Carrierwave lib:


 ##
      # Override this in your Uploader to change the filename.
      #
      # Be careful using record ids as filenames. If the filename is stored in the database
      # the record id will be nil when the filename is set. Don't use record ids unless you
      # understand this limitation.
      #
      # Do not use the version_name in the filename, as it will prevent versions from being
      # loaded correctly.
      #
      # === Returns
      #
      # [String] a filename
      #
      def filename
        @filename
      end

This is what I implemented after overriding:

def filename
    case model.type
    when :video
      "video_file"
    when :mp3
      "mp3_file"
    end
  end

Any help would be appreciated here. I wanted to change the filename if file is video or audio while uploading.

lundi 18 juillet 2022

Why are reviews of other users getting deleted in my React rails app?

I have a project with react front end and rails backend. So according to my backend code a logged in user can delete his reviews but not the reviews of other users.currently with this code one can delete the reviews of oneself ......but when one tries to delete other peoples reviews they get deleted but on reloading the page they are back??I dont want the reviews to get deleted in the first place.... I think this is a problem in the front end but im not sure.....Also is there a way to give some msg on the front end on cliking the delete button you are not allowed to do so any alert or any msg?? pls help me out here is my code .. Backend..



    def index
        review=Review.all
        render json: review

    end
    def show
        review=Review.find(params[:id])
        render json: review

    end
    def create
        review=Review.create!(review_params)
        render json: review,status: :created


    end

    def update
        review=Review.find(params[:id])
        review.update!(review_params)
        render json: review,status: :ok

    end

    def destroy
   
        review = @current_user.reviews.find(params[:id])

        if @current_user
        review.destroy
        else
            render json: {error: "Review of someone else."}, status: :not_found
        end
    end

    private
    
    def review_params
        params.permit(:image,:date,:description,:destination,:seat,:user_id,:airline_id)

    end

backend app.js

class ApplicationController < ActionController::API
  include ActionController::Cookies
  
  rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response

  before_action :authorize
   
    

    private
    def authorize

      @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

on the frontend Reviews.js


import {useParams} from "react-router-dom"
import { Link } from "react-router-dom";
import ReviewCard from "./ReviewCard";
import { useState,useEffect } from "react";
import Button from "react-bootstrap/esm/Button";
import "./Styling.css"
const Reviews = ({reviews, setReviews}) => {

  const { id } = useParams();

  useEffect(()=>{
    fetch("/reviews")
    .then(res=>res.json())
    .then(reviewData=>{
      setReviews(reviewData)
    })
  },[])

  function handleAddReviews(newReview){
    console.log("in handle add review", newReview)
    setReviews([...reviews,newReview]);
  }

  function handleDelete(id){
    let newReviews=reviews.filter(r=>r.id !== id)
    setReviews(newReviews)
  }


console.log(reviews)
  let filteredReviews = reviews.filter(review => {

    if(review.airline?.id) {
      return review.airline.id === parseInt(id);
    }

    return null;
  })

  
  return (
    <>
    <div className="reviewb">
    <Button className="reviewbuttons" variant="danger" href={"/airlines"} >Go Back</Button>
    <Button  className="reviewbuttons" variant="info" href={`/airlines/${id}/reviews/new`} >Add a Review</Button>
    </div>
      {filteredReviews.map((review) => {
        return (
          <ReviewCard key={review.id} id={review.id} review={review} handleDelete={handleDelete}  /> 
        )
      })}
    </>
  )
}

export default Reviews;

ReviewCard

import {useParams} from "react-router-dom";
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import "./Styling.css"
function ReviewCard({review,handleDelete}){
    const {id}=useParams();
    const{image,date,destination,seat,description,likes,dislikes,airline_id,user_id}=review;
   
    function handleDeleteClick() {
 
      fetch(`/reviews/${review.id}`, {
        method: "DELETE",
  
      })
      handleDelete(review.id)
      
  
    } 


    return(
        <div className="reviewcard">


        
        <img  className="cardimg" src={image} />
        <p></p>
        <h6>{date}</h6>
        <h5>{destination}</h5>
        <h5>{seat}</h5>
        <Card.Text>{description}</Card.Text>
        <Card.Title>By {review.user.name}</Card.Title>
        <p></p>
        <h6>Likes: {likes}</h6>
         <h6>Dislikes: {dislikes}</h6>

        <br/>

        <Button  className ="btn btn-success"  >👍🏻 </Button>

        <Button  className ="btn btn-danger"  >👎🏻  </Button>
        <hr />
        
        <Button  className ="btn btn-primary" onClick={handleDeleteClick}  >Delete</Button>
        
          
    
        
        </div>
    )
}
export default ReviewCard;


How to Edit and Update using Faraday Call in Rails

I tried to edit and update columns using Faraday Call on my rails app, I am successfully updating the columns by adding new value.

But I want during update, initially in edit_form, it must show my old values where i can edit it, and then update.

This is my Connection Request

def connection
        Faraday.new(url: ENV['URL'],
                    params: { clientId: ENV['CLIENT_ID'] },
                    headers: { 'Authorization' => oauth_token_generation })
end

This is my edit_request to call end point for connection and update

def edit_request(type,id, params)
        response = connection.patch("#{type}/#{id}", params)
        JSON.parse(response.body)
      rescue JSON::ParserError
        Rails.logger.error 'Invalid Json Data'
        nil
      rescue Faraday::Error => e
        Rails.logger.error "Connection Failed #{e}"
        nil
end

This is my calling method:

def self.get_entities(id,params)
      
      response = Api::Connection.edit_request('entities',id, params)
end

My Controller:

def edit
   @schemas = Api::ApiCall::Schema.get_entities(params[:id],params)
  end

def update    
end

This is my Edit Form where I want to initailly retrive all data then edit and update:

<%= form_for(:schemas, url:schemas_path) do |f| %>
      <%= f.text_field :schemaId, placeholder:"Schema Id"%>
      <%= f.text_area :name, placeholder: "Schema Name"%>
      <%= f.text_area :schemaMnemonic, placeholder: "Schema Mnemonic"%>
      <%= f.text_area :Mnemonic, placeholder: "Mnemonic"%>
      <%= f.text_area :description, placeholder: "Description"%>
      <%= f.submit "Save"%>
<% end %>

Error While Installing the tools Via RubyGems (Gem::FilePermissionError) On Windows Operating System

I am trying to install the ruby based tool in my windows 10 operating system, while installing the package via RubyGems I am getting this error :

C:\windows\system32>gem install brakeman
ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the C:/Ruby31-x64/bin directory.

Error Image

I am running this command as administrator, However still i am getting this error continusoly, Please advise me what to do

dimanche 17 juillet 2022

Ruby - undefined method `deep_transform_keys' for Array

When I'm trying to update the Network security group rules for Azure, I get the following error.

undefined method 'deep_transform_keys' for Array

Any idea why and how it can be resolved?

network_sg = Azure::Armrest::Network::NetworkSecurityGroupService.new(conf)  
network_sg.update('sg_testing_temp_1', 'cloud-shell-storage', network_sg_properties)


[----] E, [2022-07-17T16:36:12.489747 #32747:2ad3b3e0be04] ERROR -- automation: Q-task_id([r988_miq_provision_2589]) <AEMethod azure_sg_provision> The following error occurred during method evaluation:
[----] E, [2022-07-17T16:36:12.501593 #32747:2ad3b3e0be04] ERROR -- automation: Q-task_id([r988_miq_provision_2589]) <AEMethod azure_sg_provision>   NoMethodError: undefined method `deep_transform_keys' for #<Array:0x0000562e6b8e9898>
[----] E, [2022-07-17T16:36:12.503179 #32747:2ad3b3e0be04] ERROR -- automation: Q-task_id([r988_miq_provision_2589]) <AEMethod azure_sg_provision>   /opt/manageiq/manageiq-gemset/gems/azure-armrest-0.14.0/lib/azure/armrest/resource_group_based_service.rb:199:in `transform_create_options'
[----] E, [2022-07-17T16:36:12.507115 #32747:2ad3b3e0601c] ERROR -- automation: Method STDERR: from /ManageIQ_Custom/Cloud/VM/Provisioning/StateMachines/Methods/Azure_SG_Provision:268:in `<main>'
[----] I, [2022-07-17T16:36:12.534925 #32747:2ad3a008b968]  INFO -- automation: Q-task_id([r988_miq_provision_2589]) <AEMethod [/ManageIQ_Custom/Cloud/VM/Provisioning/StateMachines/Methods/Azure_SG_Provision]> Ending

vendredi 15 juillet 2022

Required specifications for the best service to 500 users of the Redmine application?

1- Required server specifications? --> RAM.CPU,DISK

2- The best operating system required? Ubuntu,debain,...

3- Nginx or apache or puma or UNicorn?

4- passenger or thin or ....?

5- best configuration for example NGINX-PASSENGER $ MYSQL ?

how to test carrierwave fog google in rspec with setting up the configuration

I have below configuration and I wanted to write TC for it in ruby. I am new to ruby and wanted to understand how we can set the configuration of Fog to point to mock and use it in test-case.

class TestUploader < CarrierWave::Uploader::Base

  storage :fog

  def fog_credentials
    {
      :provider => 'google',
      :google_project =>'my project',
      :google_json_key_location =>'myCredentialFile.json'

    }
  end


  def fog_provider
    'fog/google'
  end

  def fog_directory
    '{#bucket-name}'
  end

  def store_dir

    when :File
      "#{file.getpath}/file"
    when :audio
      "#{file.getpath}/audio"
    else
      p " Invalid file "
    end
  end
end

class TestModel

  mount_uploader :images, TestUploader

end

Could someone please assist me from configuring to write and execute the unit test on it with few example. Any help would be really appreciated.

jeudi 14 juillet 2022

logic to verify if the element is present in array from list of object

I have an 2 array with some String values. I wanted to check if one array's all value are part of another arrays. Is there any defined method available to check it or how to implement in optimised way.

Ex:

arr1['abc', 'def']

arr2['abc', 'def', 'ghi', 'jkl']

if values of array 1 is present in array 2 then only control should move ahead in code else it should return.

mardi 12 juillet 2022

Ruby - Print all methods in each loop

How can I print all methods for network_sg in the following code? I'm not sure what methods are available.

Is it possible to print all methods ? It has Name but not sure what other methods are available.

network_sg = Azure::Armrest::Network::NetworkSecurityGroupService.new(conf)

network_sg.list(rg).each do |network_sg|
    $evm.log('info', "azure network_sg test is: #{network_sg.name} ")
end

vendredi 8 juillet 2022

Record Unable to save in join table using has_many through relationship in Ruby on Rails

I am trying to create an Employee team app using join table has_many through relationship

In the team_leader column, I am going to store one employee_name and in the team_employee_name column going to store the number of employee_name using the check box. pls, help me I am stuck. Thanks

Migration

team Migration Table
 
 t.string :team_leader
 t.string :team_employee_name
 

Employee Migration Table
 
  t.string :employee_name

TeamEmployee Migration table

  t.references :team, null: false, foreign_key: true
  t.references :employee, null: false, foreign_key: true

Model

    model team

    has_many :team_employees
    has_many :teams, through: :team_employees
    
    model Employee
    
    has_many :team_employees
    has_many :employees, through: :team_employees
    
    model TeamEmployee 
    
    belongs_to :team
    belongs_to :employee

teams/index.html.erb

<%= simple_form_for(@team) do |f| %>
    <div class="field">
     #going to store one employee_name in t.string :team_leader colume
    <%= f.label "Add Leader"%>
    <%= f.select :team_employees, Employee.pluck(:employee_name)%>
     #going to store the number of employee_name using the check box in t.string :team_employee_name colume
    <%= f.label "Add users to team" %><br />
    <%= f.collection_check_boxes :team_employees, Employee.all, :id, :employee_name do |b| %>
        <div class="collection-check-box">
          <%= b.check_box %>
          <%= b.label %>
        </div>
  <% end %>
  
    <%= f.button :submit%>

  <% end %>

teams/controller.rb

class TeamsController < ApplicationController

before_action :find_team_member, only: [:show, :edit, :update, :destroy]
 def index
   @team = Team.new 
end 

 def create
    @team = Team.create(team_params)
    @team.save
    redirect_to teams_path
 end

private
  
 def find_tem_member
    @team = Team.find(params[:id])
 end

 def team_params
    params.require(:team).permit(team_employees_attributes:[{employee_attributes: [:employee_name]}],employee_id:[])
 end

end

seems I made mistake in this method pls let know

def team_params
   params.require(:team).permit(team_employees_attributes:[{employee_attributes: [:employee_name]}],employee_id:[])
end

jeudi 7 juillet 2022

Ruby - undefined method `map' for string

I'm unable to convert array of string to integer. I'm getting the following error undefined method map for "[\"118\", \"119\"]":String.

Any idea how to resolve this?

            def job_template_by_id
              job_template_id = var_search(@handle.object, 'job_template_id') ||
                                var_search(@handle.object, 'dialog_job_template_id')
                               
              job_template_id = job_template_id.map(&:to_i)

              @handle.vmdb(SCRIPT_CLASS).where(:id => job_template_id) if job_template_id
            end

Error:

[----] E, [2022-07-07T16:08:09.928258 #534:2afb827cdb68] ERROR -- automation: Q-task_id([r837_miq_provision_2172]) <AEMethod launch_ansible_job> The following error occurred during method evaluation:
[----] E, [2022-07-07T16:08:09.930286 #534:2afb827cdb68] ERROR -- automation: Q-task_id([r837_miq_provision_2172]) <AEMethod launch_ansible_job>   NoMethodError: undefined method `map' for "[\"118\", \"119\"]":String
[----] E, [2022-07-07T16:08:09.931630 #534:2afb827cdb68] ERROR -- automation: Q-task_id([r837_miq_provision_2172]) <AEMethod launch_ansible_job>   /ManageIQ_Custom/AutomationManagement/AnsibleTower/Operations/StateMachines/Job/launch_ansible_job:113:in `job_template_by_id'

`auth_data=': couldn't set additional authenticated data

really sorry for asking this, i searched a lot about this error but none seams to work for me. am new on ROR an created a new project with all configurations of ruby and rails. i have mac version 12.4 Monterey rails v: 6.0.5 ruby 2.7.2 postgresql i configure these using rbnev from this tutorial https://gorails.com/setup/osx/12-monterey and https://collectionbuilder.github.io/cb-docs/docs/software/ruby_mac/ i created new app using rails new myapp -d postgresql it's showing this error while building the project.

ERROR:

/Library/Ruby/Gems/2.6.0/gems/activesupport-6.0.5/lib/active_support/message_encryptor.rb:173:in auth_data=': couldn't set additional authenticated data (OpenSSL::Cipher::CipherError) from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.0.5/lib/active_support/message_encryptor.rb:173:in _encrypt' from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.0.5/lib/active_support/message_encryptor.rb:151:in encrypt_and_sign' from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.0.5/lib/active_support/encrypted_file.rb:76:in encrypt' from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.0.5/lib/active_support/encrypted_file.rb:50:in write' from /Library/Ruby/Gems/2.6.0/gems/activesupport-6.0.5/lib/active_support/encrypted_configuration.rb:29:in write' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/lib/rails/generators/rails/credentials/credentials_generator.rb:30:in add_credentials_file_silently' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/lib/rails/generators/rails/app/app_generator.rb:177:in credentials' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/lib/rails/generators/app_base.rb:155:in build' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/lib/rails/generators/rails/app/app_generator.rb:332:in create_credentials' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/command.rb:27:in run' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:127:in invoke_command' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in block in invoke_all' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in each' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in map' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:134:in invoke_all' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/group.rb:232:in dispatch' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/base.rb:485:in start' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/lib/rails/commands/application/application_command.rb:26:in perform' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/command.rb:27:in run' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor/invocation.rb:127:in invoke_command' from /Library/Ruby/Gems/2.6.0/gems/thor-1.2.1/lib/thor.rb:392:in dispatch' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/lib/rails/command/base.rb:69:in perform' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/lib/rails/command.rb:46:in invoke' from /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/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 /Library/Ruby/Gems/2.6.0/gems/railties-6.0.5/exe/rails:10:in <top (required)>' from /usr/bin/rails:22:in load' from /usr/bin/rails:22:in '

mercredi 6 juillet 2022

How can I display values from relationship on column array?

I have 2 tables (users and meetings).

I'm trying to displaying the name of the user on table index view

users
 |id|   |name|
  1      DEMO 1
  2      DEMO 2
  3      DEMO 3

meetings
 |id|    |user_id|
  1      ["1", "2"]
  2      ["2"]
  3      ["2", "3"]

The Controller /app/controllers/meetings_controller.erb

def index
  @meetings = Meeting.all
end

The View /app/views/meetings/index.html.erb

<table>
 <thead>
   <tr>
      <td>id</td>
      <td>User Names</td>
   </tr>
 </thead> 
 <tbody>
   <% @meetings.each do |meeting| %>
   <tr>
      <td><%= meeting.id %></td>
      <td><%= meeting.user_id %></td>
   </tr>
   <% end %>
 </tbody>
</table>

I'm trying to display the user_id on array relationship and i tried this code:

I got the following error using the following code

 undefined method `each' for "[\"1\", \"2\"]":String

 <% meeting.user_id do |array|%>
   <%= array.user.name %>
 <% end %>

I got the following error using the following code

 undefined method `each' for "[\"1\", \"2\"]":String

 <% meeting.user_id do |array|%>
   <%= array %>
 <% end %>

I cannot display the value relationship because of column array.

Can you please help me with this issue?

Thanks in advance.

not able to download image or video file from url in ruby [duplicate]

My below code snippet is not working as expected. I wanted to download the mp4 or image file from given link/URL. However my code is not working as expected. I found the similar solution over internet but it is not working. I am using ruby 3.0 version in my environment.

url = "https://images.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg?cs=srgb&dl=pexels-pixabay-60597.jpg&fm=jpg"
new_file_path = "/Users/{username}/Documents/test.jpg"
open(new_file_path, "wb") do |file| 
  file.print open(url).read
end

I am getting below error here.

test.rb:4:in `initialize': No such file or directory @ rb_sysopen - https://images.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg?cs=srgb&dl=pexels-pixabay-60597.jpg&fm=jpg (Errno::ENOENT)
    from test.rb:4:in `open'
    from test.rb:4:in `block in <main>'
    from test.rb:3:in `open'
    from test.rb:3:in `<main>'

Any suggestion here to make it work.

upload file to google bucket from remote url in ruby

We have found various solutions around upload the file to google cloud bucket from local system. However I am wondering if is there a way we can upload file to bucket using the public URL or link.

https://googleapis.dev/ruby/google-cloud-storage/latest/index.html

I want to upload a file from remote url to GCS bucket via ruby code. Any suggestion here would be really appreciated.

mardi 5 juillet 2022

GitHub Actions doesn't send slack notifications for Release failures in Heroku App

In my workflow yaml file, I have a step that sends slack notifications if the deployment step fails i.e if it exits with a non-zero exit status. The build succeeds in Heroku but the release phase fails and the app fails to deploy to the server. We don't get notified of this release failure. How can I modify the code such that it sends us release failure notifications as well? Thank you.

- name: send failure notification to slack
  if: steps.deployment.outputs.exitcode != '0'
  uses: slackapi/slack-github-action@v1.19
  with: 
    channel-id: 'insert-channel-id'
    slack-message: 'insert-slack-message'
  env:
    SLACK_BOT_TOKEN: $

lundi 4 juillet 2022

previous_changes in rails after_update for an hash field not working

I am using rails 3 and for one of the use cases, I need to detect a change in a hash field. I am making changes to the f attribute which is a hash inside the hash attribute. Something like this: Table.field = {:e=> 'hello', :f=> {"new_field"=>"In progress"}} So when I make changes to new_field it's not reflecting in previous_changes method or changes method in after_update callback. I need to trigger a few events based on this. However, it always gives {}. I tried to replace the whole field with a different value and that change is detected. Is there any other method that we can use to detect hash changes?

How to get retrieve objects in rails console in a has_many through relationship?

so i have users ,airlines and review .An airline has_many :reviews has_many :users,through: :reviews.A user has_many :reviews has_many :airlines,through: :reviews and a review belongs to an airlines and user.A user can experience multiple airlines.I dont understand a way to get all the reviews of a user of travelling by a particular airline.

here is my seed data
singapore_airlines=Airline.create(name: 'Singapore Airlines')

cathy=User.create(name:"Cathy",email:"cathy@jetsetgo.com",admin:false)


Review.create(image:"https://worldofwanderlust.com/wp-content/uploads/2022/03/866D61D2-FFD1-4392-9596-0E4E372D18D9.jpg", date: DateTime.new(2021, 11, 1),destination:"Singapore to Tokyo",seat:"Business class",description:"If you want comforting long flights always take Singapore airlines",likes:0,dislikes:0,airline_id:singapore_airlines.id,user_id: cathy.id)

so im aware in the console i can do something like sing=Airline.find(1) and then sing.reviews.........but that will give me all the reviews of singapore airline. i want only the review given by cathy.

vendredi 1 juillet 2022

How can you use distinct in rails while still using ActiveRecord's

I am struggling with the following problem: I want to have two different tabs, one that displays all recent chugs (Done), and one that displays the chugs that are the fastest per person.

However, this needs to remain an ActiveRecord, since I need to use it with link_to and gravatar, thus restraining me from group_by, as far as I understand it.

AKA: If there are three users who each have three chugs, I want to show 1 chug per user, which contains the fastest time of that particular user.

The current code looks like this, where chugs_unique should be edited:

  def show
    @pagy, @chugs_all_newest = pagy(@chugtype.chugs.order('created_at DESC'), items: 10, page: params[:page])
    @chugs_unique = @chugtype.chugs.order('secs ASC, milis ASC, created_at DESC').uniq

    breadcrumb @chugtype.name, chugtypes_path(@chugtype)
  end

In this case, a chug belongs to both a chugtype and user, and the chugtype has multiple chugs.

Thanks in advance!