vendredi 30 octobre 2020

How to add a default value to sort: in query_type.rb

Existing code in query_type.rb:

def flags(program_id:, filter: {}, sort: {})
      program = Program.find(program_id)
      context[:auth].set_current_parent_program_id(program.id)
      flags = Report.joins(:participant).where(registrants: { program_id: program.id })
      Types::Programs::FlagsFilter.get_filtered(flags: flags, filter: filter, sort: sort)
 end

I am new to Ruby and the flags are coming in reverse order (ascending) and I want to set the default value to descending. I tried setting it like this:

def flags(program_id:, filter: {}, sort: { column: 'CREATED_AT', direction: 'DESCENDING' })
      program = Program.find(program_id)
      context[:auth].set_current_parent_program_id(program.id)
      flags = Report.joins(:participant).where(registrants: { program_id: program.id })
      Types::Programs::FlagsFilter.get_filtered(flags: flags, filter: filter, sort: sort)
 end

but I'm getting an error and my flags table is no longer rendering. Any suggestions?

jeudi 29 octobre 2020

Uppercase column names from MYSQL

Have an external MYSQL DB and I am connecting it to the ruby app. All the columns are changes to uppercase and when I try to query something it works but ruby gives an undefined method error when i try to call some field from the object like:

user = User.first works but when i do user.firstname it says undefined method firstname because the user object I get has firstname column as FIRSTNAME. How can I make it a case-incentive query so either i do user.firstname or user.FIRSTNAME it works?

i tried adding ActiveRecord::ConnectionAdapters::SQLServerAdapter.lowercase_schema_reflection = true into my cofig/initializers/activereport_sqlserver_adapter.rb but still no change.

mercredi 28 octobre 2020

Ng-repeat in angularjs with rails association

I am the beginner in angular js. I'm working on the project in which I have to use ng-repeat. In the backend, I have many to many self relationships(RoR). For example, I am using model A in rails for many to many self relations. Now my question is How should I use ng-repeat to show through table along with the model itself. I have used a single model using ng-repeat=" item in items" but this approach not good in this scenario. Please guide me in this regard thankyou.

(Relation Explanation) Suppose Model A has self-relation (many to many) with itself. I need model A to show some value through Model.something along with the attribute of model A through ng-repeat. We can easily use ng-repeat for i in Model A but i need rails associated object as well.

mardi 27 octobre 2020

When and how request sometimes found to be unverified. ruby on rails 3.2

#This is the method that defines the application behavior when a request is found to be unverified. #By default, Rails resets the session when it finds an unverified request.

  def handle_unverified_request
    reset_session
  end

I have seen this explanation at "https://ift.tt/3kGBNgw" now my question is when and how every request sometimes become unverified? how it was hapenning? and when.

thankyou, i have tried to search it but i have seen explanation so deep-technical hence i can understand in an easy way

Asset pipeline error when trying to use Gemoji Gem

I getting an error whenever I try to use the gemoji gem. Does anybody know how to fix it?

app/helpers/application_helper.rb

def emojify(content)
    h(content).to_str.gsub(/:([\w+-]+):/) do |match|
      if emoji = Emoji.find_by_alias($1)
        %(<img alt="#$1" src="#{image_path("emoji/#{emoji.image_filename}")}" style="vertical-align:middle" width="20" height="20" />)
      else
        match
      end
    end.html_safe if content.present?
  end
end

enter image description here

Conditional statement in Ruby on Rails

I'm working on Jira integration in my project. I wanted to add a condition to check if project_id is generated from the valid user account (same user account). If it is generated from valid user account then show the message Jira integration is successfulotherwise Jira integration is not successful.

This is the code that I'm using.

Jira.prototype.setJiraProject = function(projects) {
    var projectField = $("#project_id"),
      projectID = $("#project_id").val();
    projectField.find('option[data-type=jira-int]').remove();
    projects.map(function(el){
      if (projectID != el[0])
        projectField.append($('<option>', { 'data-type': 'jira-int', value: el[0], text: el[1]}));
    });
    projectField.attr('disabled', false).focus();
    showError('Jira integration is successful.', 'success');
  };

Is there anyway possible to achieve it?

Less/More option disappears on closing one notification (Ruby on Rails)

I'm writing a ROR code in which a notification at top will appear if transaction fails with Less/More option. But problem occurs when user closes one notification then Less/More option disappears for the other.

This is the code that I'm using

$(document).ready(function() {
    if ( $(window).width() < 1025 ) {
    var showChar = 20;
    var ellipsestext = "...";
    var moretext = "More";
    var lesstext = "Less";
    
    $('.confirm-account').each(function() {
        var content = $(this).html();
 
        if(content.length > showChar) {
 
            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);
 
            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
 
            $(this).html(html);
        }
    });
 
    $(".morelink").click(function(){
      $('.system-message').empty();
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
  }

Is there any way possible in which the Less/More option remains there even after closing one notification?

dimanche 25 octobre 2020

How do I print out model data without printing the array?

I know that this is basic, but I cannot figure it out for whatever reason.

I'm trying to return some model data and the majority of the time I return it with pluck, but pluck is returning an array. How do I return the value without the array?

<dd><%= Goal.where(id:post.attachid).pluck(:title) %></dd>

This is the code that I have and it is returning, for example, ["Computer"]

How do I just make it return Computer

jeudi 22 octobre 2020

Not sure how to convert this type of text content to valid HTML in Ruby view

I'm not sure exactly what this type of text is called but I am having a hard time getting to convert to valid HTML. Here is an example string

\ufffd\u0004\ufffd{\u003Cp\u003E\u003Ca href=\"https://magazine.com/lifestyle/grooming/url-of-article\"\u003E\u003Cimg src=\"Vp\u0000pwp-content/uploads/2020/08/Ph\u0005x\ufffd(\u0001.jpg\"\u003E\u003C/a\u003E\u003C/p\u003ELegend has it, Ernest Hemmingway once emerged from the Ugandan jungle after surviving two plane crashes brandishing a bunch of bananas and a bottle of gin. With a poorly bandaged arm, he reportedly quipped with a wry smile \ufffd\ufffd\ufffdMy luck, she is running very good.\ufffd\ufffd\ufffd [\ufffd\ufffd\ufffd]\u003Cbr\u003E\u003Cp\u003EVisit \u003C\ufffd\ufffd\u0001\ufffd\ufffd\u0001(Magazine!\ufffdX for the full post.\u003C/p\u003E"

I need to convert the output to be valid HTML. I can remove everything and make it readable text, but I need it to also contain the HTML elements.

Sidekiq memory leak issue

I am using sidekiq gem to move my heavy reporting jobs to background. The problem is that sidekiq does not release memory even after a job is completed and it is causing an ever increasing memory bloat, resulting in sidekiq restart after every 4-5 jobs. I have tried ActiveRecord::Base.uncached and even tried this in my application.rb - config.middleware.delete "ActiveRecord::QueryCache" but still no use. Even GC.start is not working. How do I clear memory after every job?

mardi 20 octobre 2020

Send data from view page to function in controller language ruby

I have a code html dropDowns with 2 option English And Arabicand a button Save

Code in view page :

<div class="box">
          
          <div class="label-field-pair">
              <label for="languages"><%= "Choose Language" %></label>
              <div class="text-input-bg">
              <select name="language" id="language">
              <option value="english">English</option>
              <option value="arabic">Arabic</option>
              </select>
              </div>
          </div>

         <div id="submit-button">
              <%= submit_tag "► #{t('save')}" %>
          </div> 
      </div>

When i choose 1 of option and click in save button i want to send data to fucntion in controller

Controller :

class LanguagesController < ApplicationController
  def save
    

    
  end
end

Function save only get data of option (English or Arabic) and update table language in database. Easy to me to update table but i don't know how to get data from view to function in controller.

Code in ruby

Ruby on rails Please give me the basics of using gem devise

I would like to create a simple login system as shown in this picture. I am currently practicing writing in Ruby on rails language, I will try to understand it and continue to work on it.

Please give me a detailed description. Thank you.

enter image description here

enter image description here

enter image description here

lundi 19 octobre 2020

Can't print data "name" ruby on rails

I am trying to print data from a object "root" to a table, everythink work fine but not printing this name i dont know why.

Code :

<% root = NameOfDatabase.find_by_student_id(student.id) %>
            <%  logger.info root.inspect %>
            <% if root.nil? %>
           <td class="col-4"> <% "-" %> </td>
           <%  else %>
           <td class="col-4"> <% root.name %> </td>
           <% end %>

Picture: View

Log file :

...  
#<Name**** id: ****, student_id: ****, name: "Alice", school_id: ****>
Completed in 99ms (View: 7, DB: 33) | 200 OK [https://*********/new_students/search_ajax?option=active&query=s001]

As following in root we have data i want only print root.name in table !!

thanks you

mardi 13 octobre 2020

Is there a way to use a where statement with multiple tables?

I have three tables

Table name: follows
#
#  id         :bigint           not null, primary key
#  following  :bigint
#  requestor  :bigint
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  user_id    :bigint
#
# Indexes
#
#  index_follows_on_user_id  (user_id)
    belongs_to(
        :user,
        class_name: 'User',
        foreign_key: 'user_id',
        inverse_of: :follows
    )
User
has_many(
    :follows,
    class_name: 'Follow',
    foreign_key: 'user_id',
    inverse_of: :user
  )

Post
belongs_to(
        :user,
        class_name: 'User',
        foreign_key: 'user_id',
        inverse_of: :posts
    )

The requestor column takes a user.id.

I would only like to show the Posts where the requestor attribute == current_user.id. Am I only able to do this with a join or is there a way to do this with a where statement?

How do I use image_tag in

I'm trying to use the code below to display a user avatar picture. This picture can be accessed by using <%= image_tag(@user.avatar) %>

I'm unsure of how to replace the src= in the code below because previous attempts to replace it ended in failure.

<img class="rounded-circle" width="45" src="https://picsum.photos/50/50" alt="">

Previously I use to used <%= image_tag(@user.avatar, style: 'width:50%') %> to show images, but I prefer the styling of the <img class> more. If anybody can help we out with this on point me into the direction of some documention on this I would greatly appreciate it

lundi 12 octobre 2020

uninitialized constant Faraday::Error::ConnectionFailed in elastic-search

I'm implementing elastic-search in rails by following this tutorial

https://iridakos.com/programming/2017/12/03/elasticsearch-and-rails-tutorial

And add these lines to my User.rb include Elasticsearch::Model include Elasticsearch::Model::Callbacks & also installed these two gems gem 'elasticsearch-model' gem 'elasticsearch-rails' but when I try to execute this command Post.import(force: true) it gives me an error

uninitialized constant Faraday::Error::ConnectionFailed

vendredi 9 octobre 2020

jeudi 8 octobre 2020

AWS SecretsManager password rotation does not work in Rails

We are using AWS SecretsManager (SM) to store a rotating database password for our rails app. However, when SM rotates the password, we get "FATAL: password authentication failed for user".

The password is read in database.yml

password: '<%= AwsSecretService.new.get_db_pwd(ENV['DATABASE_USERNAME']) if Rails.env.production?   %>'

The problem appears to be that ActiveRecord is caching the database credentials from database.yml upon initialization and does not reparse database.yml.

My thought is to somehow trap the authentication failed error and reinitialize ActiveRecord. With the following command:

ActiveRecord::Base.establish_connection(::Rails.application.config.database_configuration[::Rails.env]) 

I'm not sure how to trap the error. Would I need to put an error handler in application_record.rb since all activerecord models inherit from it?

Or would it be better to use an Observer of some sort?

Ideas?

How to destroy model with values

I'm kind of new to rails. I have a model called follows that has to values (requestor and following). I am having trouble creating a button that destroys a select model with two valuesenter image description here



<dt>User ID:</dt>
<dd><%= @user.id %></dd>

<dt>User email:</dt>
<dd><%= @user.email %></dd>

<% if Follow.where(:requestor => current_user.id, :following =>@user.id).present? %>    
    <%= button_to 'Unfollow', follow_url, method: :delete, class: "text-danger", data: { confirm: 'Are you sure?' } %>
<% else %>
    <%= button_to "Follow", {:controller => 'follows', :action => 'create', :requestor => current_user.id, :following => @user.id}, {:method => :post} %>
<% end %>

The Follow button below in the else statement works, but I cannot figure out how to get the destroy button to work. I'm executing these buttons on the User show page instead of on the follow index.enter image description here

def destroy
    @follow.destroy
    respond_to do |format|
      format.html { redirect_to follows_url, notice: 'Follow was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_follow
      @follow = Follow.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def follow_params
      params.permit(:requestor, :following)
    end
    def require_permission
      if Follow.find(params[:id]).user != current_user
        redirect_to goals_url, flash: { error: "You do not have permission to do that."}
      end
    end
end

I keep getting couldn't find Follow with 'id' error. It deletes sometimes, but the majority of the time I get this error.enter image description here

Routes. uses general format

require 'sidekiq/web'

Rails.application.routes.draw do
  resources :follows
  resources :accounts
  resources :goals
  resources :retirements
  get '/users', to: 'users#index'
  get '/user/:id', to: 'users#show', as: 'user'
  resources :calculate_debts
  get '/privacy', to: 'home#privacy'
  get '/terms', to: 'home#terms'
    authenticate :user, lambda { |u| u.admin? } do
      mount Sidekiq::Web => '/sidekiq'
    end


  resources :notifications, only: [:index]
  resources :announcements, only: [:index]
  devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
  root to: 'home#index'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

Savon::SOAPFault: (s:Client) Element 'RequestContext' is missing from the header

I am using savon gem in rails to call purolator E-Ship soap APIs,

gem 'savon', version 2.12.0

Here is my code sample where I am calling the actual API

@client = Savon.client(wsdl: "#{Rails.root.to_s}/app/carriers/wsdls/purolator/tracking_service/TrackingServiceDev.wsdl",
              "soap_header" => {
                "RequestContext" => {
                  "Version" => '1.2',
                  "Language" => 'en_US',
                  "GroupID" => 'xxx',
                  "RequestReference" => 'Rating Example'
                }
              },
              :basic_auth => ["xxxxxxxxxx", "xxxxxxxxx"], 
              :log => true, :pretty_print_xml => true, :element_form_default => :unqualified)
body = {
      "PIN" => {
        "Value" => 329014521622
      }
    }
@client.call(:get_delivery_details, message: body).body

Here is the Request XML that is being generated and displayed by Savon

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q12="http://purolator.com/pws/service/v1" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ins0="http://purolator.com/pws/datatypes/v1" xmlns:ins1="http://www.microsoft.com/practices/EnterpriseLibrary/2007/01/wcf/validation" xmlns:ins2="http://schemas.datacontract.org/2004/07/Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF">
  <env:Header>
    <RequestContext>
      <Version>1.2</Version>
      <Language>en_US</Language>
      <GroupID>xxx</GroupID>
      <RequestReference>Rating Example</RequestReference>
    </RequestContext>
  </env:Header>
  <env:Body>
    <q12:GetDeliveryDetailsRequest>
      <PIN>
        <Value>329014521622</Value>
      </PIN>
    </q12:GetDeliveryDetailsRequest>
  </env:Body>
</env:Envelope>

and here is the response I am getting back from the API

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode>s:Client</faultcode>
      <faultstring xml:lang="en-CA">Element 'RequestContext' is missing from the header</faultstring>
    </s:Fault>
  </s:Body>
</s:Envelope>

API is throwing an error message that Element 'RequestContext' is missing from the header but I provided this header and it is displayed in request as well. Can anyone please point me in the right direction and let me know what I am missing here.

mercredi 7 octobre 2020

How to import from JS and not put in the script

I implemented these 4 scripts in my head in ruby ​​on rails:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/animation.gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.0.1/dist/gsap.min.js"></script>

So, ScroolMagic, animation gsap, debug indicators and gspa. But in Ruby on Rails it's better to create a separated folder/file to protect and seperate your js code.

So for gsap it's ok. I did this inside my js.file in my javascript folder:

    import { gsap } from "gsap";

But for the 2 others (debug.addIndicators is not a priority) i don't know how to do, i tried a lots of possibilities like:

 import { ScrollMagicPluginGsap } from "scrollmagic-plugin-gsap";
    import ScrollMagic from 'ScrollMagic';
    import * as ScrollMagic from 'ScrollMagic';

and more... can someone help me please?

No method error undefined method `each' in ruby

i try to write a function get meeting details from table online meeting rooms i specific 3 parameter: start_date & end_date & username this function should return api in formate : details[Name] = ... & details[...] = ... as following in code In database we have multiple colon and data i want only name and sheduled_on and condition between 2 date as parameter I dont understand what is the error in my code ?

Error :

hh
2
1
[FedenaRescue] No method error undefined method `each' for #<BbbMeetingRoom:0x7fd0261d3be0>

NoMethodError (undefined method `each' for #<BbbMeetingRoom:0x7fd0261d3be0>):
  vendor/plugins/madrasatie_api/app/controllers/api/meetingapi_controller.rb:35:in `get_meeting'
  passenger (4.0.59) lib/phusion_passenger/rack/thread_handler_extension.rb:74:in `process_request'
  passenger (4.0.59) lib/phusion_passenger/request_handler/thread_handler.rb:141:in `accept_and_process_next_request'
  passenger (4.0.59) lib/phusion_passenger/request_handler/thread_handler.rb:109:in `main_loop'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:455:in `start_threads'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:449:in `initialize'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:449:in `new'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:449:in `start_threads'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:448:in `times'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:448:in `start_threads'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:447:in `synchronize'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:447:in `start_threads'
  passenger (4.0.59) lib/phusion_passenger/request_handler.rb:208:in `main_loop'
  passenger (4.0.59) helper-scripts/rack-preloader.rb:161

Rendering single_access_tokens/500.xml

My Code :

class Api::MeetingapiController < ApiController
  require 'net/http'
  require 'json'
  require 'net/https'
  require 'securerandom'
  
  helper_method :https
 
  def get_meeting
    logger.info "hh"
    @start_date = params[:start_date].present? ? params[:start_date].to_date : @local_tzone_time.to_date
    @end_date = params[:end_date].present? ? params[:end_date].to_date : (@local_tzone_time).to_date
    @user = User.active.first(:conditions => ["username LIKE BINARY(?)",params[:username]])
    @details = []
    if @user.admin?
      @rooms = OnlineMeetingRoom.find_all_by_date(:conditions=>"( Date(scheduled_on) between '#{@start_date}' and '#{@end_date}' or Date(scheduled_on) = '#{@start_date}' or Date(scheduled_on) = '#{@end_date}' )",:order=>"id DESC")
      logger.info "2"
      else
    logger.info "here1"
    @rooms = OnlineMeetingRoom.valid_meetings
    logger.info "here2"
    @rooms = @rooms.rooms_for_user(@user)  unless @user.admin? 
    logger.info "here3"
    @rooms = @rooms.scheduled_on_gte(@start_date).scheduled_on_lte(@end_date.end_of_day)
    logger.info "here4"
      end
    
    logger.info "1"
       
    @rooms.each do |r|
    room = Hach.new
    logger.info "555"
    room["Name"] = r.name
    logger.info "666"
    room["Created_by"] = @user
    logger.info "999"
    room["Shedule on"] = r.sheduled_on
    logger.info "000"
    @details << room
  end
  respond_to do |format|
        format.json {render :json=>{ :data => {:details =>JSON.parse(@details.to_json.gsub("'", %q(\\\')))}, :statusCode => 200, :statusMessage => "OK" }}

     end
  end
  end 
 

mardi 6 octobre 2020

Problem with nio4r gem: An error occurred while installing nio4r (1.2.1), and Bundler cannot continue

Hi everyone I have just started using ruby ​​on rails I have a problem when I go to effect "bundle update" gives me this error:

"An error occurred while installing nio4r (1.2.1), and Bundler cannot continue. Make sure that gem install nio4r -v '1.2.1' succeeds before bundling. "In Gemfile: devise_token_auth was resolved to 0.1.40, which depends on rails was resolved to 5.0.0, which depends on actioncable was resolved to 5.0.0, which depends on nio4r

Ruby version:2.3.0

I tried to run various commands like:

bundle config build.nio4r --with-cflags="-std=c99" brew update

but they didn't work

How to retain PORO Form object field inputs?

I've created a R-o-R Form object which takes in attributes and then saves those attributes to some nested objects, however, upon failing the validations, the input values disappear. Is there anyway to retain them?

class FormObject
 include ActiveModel::Model
 attr_accessor(:name, :date)
 
 def initialize(params = {})
  @params = params
 end

 def save
  return if invalid?
  no = NestedObject.new(nested_object_params)
  no.save
 end

 def nested_object_params
  @params.permit(:name, :date)
 end
end

and this is the controller

class Controller
 def new
  @form = FormObject.new
 end

 def create
  @form = FormObject.new(form_object_params)
  if @form.save
    redirect_to ...
  else
    render :new
  end
 end

 def form_object_params
  params.require(:form_object).permit(:name, :date)
 end
end

lundi 5 octobre 2020

I am getting an ActiveJob::DeserializationError when trying to attach photo while seeding

I am trying to learn how to use active storage and AWS. I am attempting to give Users the option of having a picture and I managed to make it work within my app, but am stuck when trying to give users in my seed file photos.

Right now some problematic code in my seeds file is:

User.destroy_all

user = User.create!(
    id: "1",
    email: "admin",
    password: "admin1"
)

file = File.open('app/assets/images/robot-avatar.png')
user.photo.attach(io: file, filename: 'robot-avatar.png')

When I run rails db:seed, I'm receiving an error which states:

ActiveJob::DeserializationError: Error while trying to deserialize arguments: Couldn't find ActiveStorage::Blob with 'id'=17

Im still pretty new to coding in general, and extremely new when it comes to Active Storage/AWS, so any help would be appreciated. Thanks

regex input path string [duplicate]

Hey so im new to Regex but what im basically trying to do is have the user input a path and just check if my current string contains any matching paths. So for example

Paths = "/cookie /cookie/iceCream /"
rexexInput = "/coo"

if(paths.match(regexInpute))
  //do something
end

so basiaclly just checking if the user input path is contained within the string