mardi 30 avril 2019

How to trigger different links to pages for different roles?

I am developing a website for different characters(or Roles) to use by using Ruby on Rails. Ruby: 2.6.0, Rails:5.2.2, Devise.
I want to create a webpage to show different country names. In 'index' page, it will show 'France', 'Switzerland' and 'China'. For different characters(or Roles), they have different permissions, ex: "Global Manager" can click 'France', 'Switzerland', 'China'; "Asia Manager" can only click 'China', and show 'No Permission!' if clicking 'France' or 'Switzerland'.

What I am trying now is using 'if...elsif...else' in 'index.html.erb' and 'countrycheck.html' with conditions of different email address domain. The problem I met is: I login in as 'test01@france.com'(Global Manager). I can see three countries' names in index page(correct), but I get the same page for 'France' title no matter which country I click. I know the error is because in my code 'france.com' matches 'France' page.

How to modify the codes? Is there any better way to realize the functionality? Thanks!

'Index.html.erb'

   <% if current_user.email.split("@").last == "france.com" && current_user.character != "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "France", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
            <% elsif current_user.email.split("@").last == "switzerland.com" && current_user.character != "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "Switzerland", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
            <% elsif current_user.email.split("@").last == "china.com" && current_user.character != "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "China", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
            <% elsif current_user.character == "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "France", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
                 <br>
                 <br>
                 <li><%= link_to "Switzerland", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
                 <br>
                 <br>
                 <li><%= link_to "China", "http://localhost:3000/maisoncheck.html", :class => "choices" %></li>
            <% else %>
                 <br>
                 <br>
                 <li><%= link_to "Other Countries", "http://localhost:3000/maisoncheck.html", :class => "choices" %></li>
            <% end %>

'countrycheck.html.erb'

<% if current_user.email.split("@").last == "france.com" %>
            <h1><%= link_to "France", "#"%></h1>
        <iframe>some iframe information related to France</iframe>
        <% elsif current_user.email.split("@").last == "switzerland.com" %>
            <h1><%= link_to "Switzerland", "#"%></h1>
        <iframe>some iframe information related to Swizterland</iframe>
        <% elsif current_user.email.split("@").last == "china.com" %>
            <h1><%= link_to "China", "#"%></h1>
       <iframe>some iframe information related to China</iframe>
        <% else %>
                <iframe> other countries iframe information </iframe>
        <% end %>

country_controller.rb

class CountryController < ApplicationController

    before_action :authenticate_user!
    before_action :check_admin

    def index
        @users = User.all
    end

    def show
        @users = User.all
    end

    def countrycheck
        if current_user
        else
            flash[:alert] = "No permission!"
            redirect_to "http://localhost:3000/country.html"
        end
    end

    protected

    def check_admin
        unless current_user.character == "Global Manager" || "Regional Manager"
          flash[:alert] = "No permission!"
          redirect_to "http://localhost:3000/introduction.html"
         return
        end
    end
end

lundi 29 avril 2019

ActionController::UrlGenerationError in Interfaces#index

I am trying to delete my interface,and it said No route matches {:action=>"show", :controller=>"interfaces", :project_id=>#}, missing required keys: [:id].

Because I do not which arguments should be put into <%=link_to '删除', project_interface_path()%>

I have tried many different arguments into a path.

It is my interface_controller.rb file:

def destroy
    @interface = @proeject.interfaces.find(params[:project_id])
    if @interface.destroy
      redirect_to project_interfaces_path
    end
end
  def index
    @interfaces = Interface.all
    @project = Project.find(params[:project_id])

  end
  def new
    @project = Project.find(params[:project_id])
    @interface = Interface.new
  end

  def create
    @project = Project.find(params[:project_id])
    @interface = @project.interfaces.new(interface_params)
    if @interface.save
      redirect_to project_interfaces_path
    else
      render :new
    end
  end
 It is my interface/index.html.erb

 <% @interfaces.each do |interface| %>
      <tr>
        <th scope="row">1</th>
        <td><%=interface.name %></td>
        <td><%=interface.desp %></td>
        <td><%=interface.method_type_id %></td>
        <td><%=interface.request_url %></td>
        <td><%=interface.request_eg %></td>
        <td><%=interface.response_eg %></td>
      </tr>
      <td><%= link_to '删除', project_interface_path(interface),method: :delete, data:{confirm:'确定要删除吗?'}, class: 'badge badge-dark' %></td>

dimanche 28 avril 2019

Is there any way to combine similar html.erb file in views & actions in controller?

I am building a website by using ruby on rails. There is a country list. By clicking different country names , it will link to webs which show information related to this country. These webs are quite similar. Even more, people only have permission to country which they come from. Now, I create several html.erb files under 'views'->'country' folder, and several actions in 'Country' controller. It works, but I want to make codes more efficient. Is there any way to combine these similar html.erb files into one html.erb file and combine actions to one action in controller? Use 'if...else...'? Any suggestions are welcome and thankful.

enter image description here

   class CountryController < ApplicationController
before_action :authenticate_user!
before_action :check_admin

def index
    @users = User.all
end

def show
    @users = User.all
end

def france
    unless current_user.email == "test@france.com"
        flash[:alert] = "No permission!"
        redirect_to "http://localhost:3000/country.html"    
    end
end

def switzerland
    unless current_user.email == "test@switzerland.com"
        flash[:alert] = "No permission!"
        redirect_to "http://localhost:3000/country.html"    
    end
end

def china
    unless current_user.email == "test@china.com"
        flash[:alert] = "No permission!"
        redirect_to "http://localhost:3000/country.html"    
    end
end

protected
    end

expected result: combine similar html.erb files into one html.erb file and combine actions to one action in controller

vendredi 26 avril 2019

Rails (Object doesn't support #inspect) / NoMethodError (undefined method `[]' for nil:NilClass)

I have a model "Section". Whenever I try to iterate over Section object, like, "Section.all" or "Section.create", I get error as "(Object doesn't support #inspect)" in rails console and "NoMethodError (undefined method `[]' for nil:NilClass)" in the terminal.

I really need some help since it has become a road blocker.

Ruby : ruby 2.6.1p33

Rails : 5.2.3

Section migration

class CreateSections < ActiveRecord::Migration[5.2]
  def change
    create_table :sections do |t|
      t.string :name
      t.integer :students_count, :default => 0
      t.references :class, index: true
      t.references :class_teacher, index: true

      t.timestamps
    end
    add_foreign_key :sections, :standards, column: :class_id
    add_foreign_key :sections, :users, column: :class_teacher_id
  end
end

Section model

class Section < ApplicationRecord
  belongs_to :class, :class_name => "Standard", :foreign_key => "standard_id"
  belongs_to :class_teacher, :class_name => "User", :foreign_key => "class_teacher_id"
end

Controller code

def index
  @sections = Section.where(:class_id => params[:class_id])

  render json: @sections
end

Terminal output

NoMethodError (undefined method `[]' for nil:NilClass):

Rails console Input

Section.all

Rails console output

(Object doesn't support #inspect)

Strangely, when Section table is empty, console output is

#<ActiveRecord::Relation []> 

Thanks in advance.

jeudi 25 avril 2019

Polyline straight instead of snapping to road on Ruby app

I have added the following code to display a map and draw a path on it. There could be many points to display (So start, waypoints and end). The points are all in a table Location which has both latitude and longitude fields. I am not sure how to pass the information so that the table shows up and the path connected the different stops

<script>
    var map_options = {
        center: new google.maps.LatLng('<%= current_user.latitude %>', '<%= current_user.longitude %>'),
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        panControl: false,
        mapTypeControl: false,
        zoomControlOptions: { position: google.maps.ControlPosition.LEFT_CENTER }
    };

    var map = new google.maps.Map(document.getElementById("map-canvas"), map_options);
    var apiKey = '<%= Rails.application.secrets.google_secret%>';

    function processSnapToRoadResponse(data) {
        snappedCoordinates = [];
        placeIdArray = [];
        for (var i = 0; i < data.snappedPoints.length; i++) {
            var latlng = new google.maps.LatLng(
                data.snappedPoints[i].location.latitude,
                data.snappedPoints[i].location.longitude);
            snappedCoordinates.push(latlng);
            placeIdArray.push(data.snappedPoints[i].placeId);
        }
    }

    function drawSnappedPolyline() {
        var snappedPolyline = new google.maps.Polyline({
            path: snappedCoordinates,
            strokeColor: 'black',
            strokeWeight: 3
        });

        snappedPolyline.setMap(map);
        polylines.push(snappedPolyline);
    }



    function runSnapToRoad(path) {
        var pathValues = [];
        for (var i = 0; i < path.getLength(); i++) {
            pathValues.push('???????????????????');
        }

        $.get('https://roads.googleapis.com/v1/snapToRoads', {
            interpolate: true,
            key: apiKey,
            path: pathValues.join('|')
        }, function(data) {
            processSnapToRoadResponse(data);
            drawSnappedPolyline();
        });
    }






</script>

Does anybody knows how to pass the array of longitude/latitude? I have checked the following links: http://www.kadrmasconcepts.com/blog/2013/06/28/drawing-polylines-with-rails-and-google-maps/ This one does not show how he gets the path, as a result when using his path it is fine, but when creating my own path, I get a straight line.

https://developers.google.com/maps/documentation/roads/snap This is the current code that I used.

Call windows exe file from rails application

I am calling exe file from rails application.I have set-up rails application over windows machine and from code I am running exe file.In this I need to pass a path in the arguments.

@project = Project.find(params[:project_id])
xml_file_path = @project.xml_file_name
basename = File.basename(xml_file_path) i.e "12.xml"

Tried this -

final_xml_path = "C:\Windows\System32\workspace\preference\public\xml_files\#{basename}"

I have tried this -

 final_xml_path = 'C:\\Windows\\System32\\workspace\\preference\\public\\xml_files\\#{basename}'

Output - p final_xml_path

"C:\\Windows\\System32\\workspace\\preference\\public\\xml_files\\\#{basename}" 

Desired output -

final_xml_path = "C:\Windows\System32\workspace\preference\public\xml_files\12.xml"

I need this output I need to pass in the arguments while running exe file.

mercredi 24 avril 2019

ArgumentError in StaticPages

I had a working pagination but after some changes to the gemfile, all the pagination started throwing this error wrong number of arguments (given 0, expected 1)

The gemfile changes have brought the errors on every class that needs pagination so it could be an issue about how I am handling the gem. The error is here Showing /home/ec2-user/environment/homework_helper/app/views/assignments/assignment/_homework_answers_page.html.erb where line #3 raised:

  <%= will_paginate @assignments  %> -line  3


      <% @assignments.each do | assignment | %>

      <tr>


gem 'will_paginate',           '3.1.6'
gem 'will_paginate-bootstrap4'


 def homework_answers
   @assignment = Assignment.new
   @categories = Category.all
   @assignments = Assignment.all
   @assignments =  Assignment.paginate(page: params[:page], per_page: 10)
  end

Phusion passenger is overriding my database config

I am using nginx with Phusion Passenger to bootload a ruby on rails application, if I run the application like

rails s -e production

It does connect correctly to the database, but when bootloaded from nginx with passenger it tries to use root to the database, like ignoring the config files.

I already tried giving permissions, but doesnt look like there is the problem, I already opened the 3 possible host names for root, which could be "localhost", "%" and "127.0.0.1", but in any case it should be openning a connection with root

I would say something is weird on how passenger behaves or that somewhere (not in the app) is ignoring the database.yml or overriding the credentials

mardi 23 avril 2019

Do partial variables override helper methods?

I have some helper method that called current_language and sometimes I send current_language in the local_assigns.

So I want to assign my partial variable by the local_assigns's current_language in case if it's sent.

But I found something weird, in the following code:

<%
  binding.pry
  x = 4

  current_language = local_assigns[:current_language] || current_language
%>

In line 3 when debugging current_language equals nil even before overriding.

I expect it shall still equal the helper method until it's overrided.

So what is going on?

lundi 22 avril 2019

calling send_data with filepath, file is getting deleted and send_data throwing "No such file or directory @ rb_sysopen"

I am trying to download xls file using send_file file_path, :content_type => "application/vnd.ms-excel", :filename => File.basename(file_path) But getting error as "No such file or directory @ rb_sysopen".

I am using rails 3.2.21 and corresponding actionpack 3.2.21

I have added File.exist?(file_path) which is returning true. But on execution of send_file method the file is getting deleted and throwing error. Below is stacktrace

App 9174 stderr: [ 2019-04-22 17:01:07.8144 9229/0x005579aae50758(Worker 1) utils.rb:85 ]: *** Exception Errno::ENOENT in Rack response body object (No such file or directory @ rb_sysopen - /usr/share/app_name/public/data-20190422-170057.xls) (process 9229, thread 0x005579aae50758(Worker 1)):
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/actionpack-3.2.21/lib/action_controller/metal/data_streaming.rb:93:in `initialize'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/actionpack-3.2.21/lib/action_controller/metal/data_streaming.rb:93:in `open'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/actionpack-3.2.21/lib/action_controller/metal/data_streaming.rb:93:in `each'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/actionpack-3.2.21/lib/action_dispatch/http/response.rb:44:in `each'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/activerecord-3.2.21/lib/active_record/query_cache.rb:46:in `each'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/activerecord-3.2.21/lib/active_record/connection_adapters/abstract/connection_pool.rb:460:in `each'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/rack-1.4.7/lib/rack/body_proxy.rb:31:in `each'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/passenger-5.0.15/lib/phusion_passenger/rack/thread_handler_extension.rb:297:in `process_body'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/passenger-5.0.15/lib/phusion_passenger/rack/thread_handler_extension.rb:143:in `process_request'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/passenger-5.0.15/lib/phusion_passenger/request_handler/thread_handler.rb:157:in `accept_and_process_next_request'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/passenger-5.0.15/lib/phusion_passenger/request_handler/thread_handler.rb:110:in `main_loop'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/passenger-5.0.15/lib/phusion_passenger/request_handler.rb:415:in `block (3 levels) in start_threads'
App 9174 stderr:        from /usr/lib/ruby-flo/lib/ruby/gems/2.2.0/gems/passenger-5.0.15/lib/phusion_passenger/utils.rb:111:in `block in create_thread_and_abort_on_exception'
[ 2019-04-22 17:01:07.8150 9011/7efd5ffff700 Ser/Server.h:929 ]: [Client 1-2] Disconnecting client with error: error parsing app response chunked encoding: unexpected end-of-stream

This was working with rails 3.1.3 but due to our OS upgradation we have to upgrade rails 3.2.21 and this is getting break. Let me know if any other input I should provide.

jeudi 18 avril 2019

How can i display my radio_button checkbox + label on the same line

I can't align label + radio_buttoms on my simple_form. I tried almost everything by adding some classes + display : inline-flex ...

I tried to put classe though wrapper_html, import_html + display flex / display : inline-flex ....

<%= simple_form_for (@dog), html: { multipart: true } do |f| %>
   <div class="row">
          <div class="col-xs-12 cols-sm-12 legend-radio-buttons">
          <%= f.input :experience,
               as: :radio_buttons,
               label:"A t-il déjà ?",
               collection: [['0', 'Non'], ['1', 'Oui']],
                label_method: :second,
                value_method: :first,
                import_html: {class: 'radio_buttons'}
                    %>
           </div>
       </div>

CSS

form-check {
    display: inline-block;
 }

 .col-form-label.pt-0{
 font-family: "Roboto Condensed" !important;
 font-size: 14px !important;
  }


.radio_buttons {
    font-family: "Roboto Condensed";
    font-size: 15px !important;
}

.form-check-input.radio_buttons.optional {
    margin-right: 10px;
 }

I would like something like this (radio_buttons are represent by + ) :

     A t-il déjà ?    Oui +     Non +

mercredi 17 avril 2019

Rails API App ignores Accept-Language header value

This is all at the Controller level, ie ApplicationController.

This is a really strange issue which may only be occurring to me.

Basically, as the title says Rails is ignoring the Accept-Language header value. But get this, order matters apparently.

So if I curl

curl -X POST \
 http://localhost:1234/signin \
 -H 'Accept-Language: de' \
 -H 'content-type: application/json' \
 -H 'Test-Header: Test' \

I can access the Accept-Language value with request.headers['Accept-Language'] perfectly fine.

However, if I change the order

curl -X POST \
 http://localhost:1234/signin \
 -H 'content-type: application/json' \
 -H 'Accept-Language: de' \
 -H 'Test-Header: Test' \

request.headers['Accept-Language'] returns nil.

Any idea as to why this may happen? I'm on Rails 3.2.22.1

Things I've done:

  • Checked the Rack::Cors middleware
  • Pulled out my hair
  • Verified header is sent both on curl and web, also verified my findings with Postman
  • Global search to see if it gets overwritten anywhere (I couldn't find anything)
  • Other header values are fine. I didn't test all of them but did test custom and a handful of others.

Thanks in advance!

I want to change default label YES NO of my checkbox radio_button from my f.input (form_for)

I'm starting using Rails.

In my form_for, I want to change label of default value YES / NO (which appear in my front view)

        <div class="row">
            <div class="col-sm-6">
              <%= f.input :experience,
                   as: :radio_buttons,
                   label:"A t-il déjà saillie ?"  %>
           </div>
        </div>

Which option should I add to change label ? How can I display option in one line ?

Thank you for your help

mardi 16 avril 2019

How to select rows in table using checkboxes and pass as parameters to controller

I have a table which displays a list of items. I'm trying to be able to select a few of the items in this table and pass to my controller where I hope to only render the specifically selected items.

# 'products/index.html.haml'
%table.table
  %thead
    %tr
      %th Select
      %th Id
      %th Short description

  %tbody
    - @products.each do |product|
      %tr
        %td
          %input{ :type=>"checkbox", :checked=>"checked", :name=>"selected_products[]", :value=>product.id}
        %td
        %td= product.id
        %td= product.short_description

= link_to 'View selected', product_path(:selected_ids=>SELECTED_PRODUCT_IDS)

As shown above it displays a table where the first column is a selected checkbox with its value being its corresponding product.id - I'm trying to pass an array of those id's selected into the parameters - i.e the array SELECTED_PRODUCT_IDS.

# 'controllers/product_controller.rb'
def index
   product_ids = params[:selected_form_datums]
   ...

Above shows my controller getting access to this array. I've seen a few answers to similar questions suggesting to put this into a 'form_for' tag however all my attempts have doing this have so-far failed.

Would appreciate any help.

getting error while using nested form in rails

I am using nested form in rails , parameters are coming in console but not save into the database table error : Unpermitted parameter: shyain_rekis

is there mistake in aru_params ? if there then what is the mistake please help me

thank you

def aru_params
  params.require(:aru).permit(:shyain_rekis_attributes => [:id, :emp_type, :company_leaving_reason, :_destroy])
end

Parameters: {"shyain_rekis_attributes"=>{"1555403656594"=> {"shyain_rekis"=>{"emp_type"=>"abc",company_leaving_reason"=>""}, "_destroy"=>"false"}}

I want to resolve error and save data into database table of nested form

lundi 15 avril 2019

How can I found out were my ROR app is getting its ENV variables

I took over a ROR app and I have changed ENV vars in local_env.yml and in .env to point to a new MongoDB server on MongoDB Atlas and away from MLab.

However, the app is still hitting the db on MLab. I checked the computer and there were the same ENV in bash_profile, which I have changed. I then did a source ~/.bash_profile and then restart Puma but the app is still using Mlab DB which is reached via ENV[MONGO].

Ruby: two ways using try in Hash

I want to extract a value by using try in Ruby.

I found there are two ways of doing this and was playing around with it in irb.

>> hash = { a: 1, b: 2 }
=> {:a=>1, :b=>2}
>> hash.try(:a)
=> nil
>> hash.try(:[], :a)
=> 1

I have two questions,

  1. What is the difference between hash.try(:[], :a) and hash.try(:a)? I searched around and found people use both ways.
  2. I saw a lot of places using hash.try(:a) to retrieve values, but why my trial returns nil?

How to save a Ruby language program?

I do not know how to save a file in Ruby language using. rb file extension. This is my problem. can anyone tell me and solve my problem.

Send foreign key objects with all child or children objects

is there any way to always retrieve parent objects with the child or children object for a rails API only application ?

e.g. I have a @students array. Each student object in @students array has two foreign keys as standard_id and school_id. Now all the objects have by default standard_id and school_id. Instead I want standard object and school object in each student object in the @students array.

The response which I get

[
  {
    "id": 1,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:36:03.000Z",
    "updated_at": "2019-04-14T11:36:03.000Z"
  },
  {
    "id": 2,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:41:38.000Z",
    "updated_at": "2019-04-14T11:41:45.000Z"
  }
]

The response which I want

[
  {
    "id": 1,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:36:03.000Z",
    "updated_at": "2019-04-14T11:36:03.000Z",
    "standard": {
      "id": 1,
      "name": "1",
      "created_at": "2019-04-14T11:32:15.000Z",
      "updated_at": "2019-04-14T11:32:15.000Z"
    },
    "school": {
      "id": 1,
      "name": "SACS",
      "created_at": "2019-04-14T11:35:24.000Z",
      "updated_at": "2019-04-14T11:35:24.000Z"
    }
  },
  {
    "id": 2,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:41:38.000Z",
    "updated_at": "2019-04-14T11:41:45.000Z",
    "standard": {
      "id": 1,
      "name": "1",
      "created_at": "2019-04-14T11:32:15.000Z",
      "updated_at": "2019-04-14T11:32:15.000Z"
    },
    "school": {
      "id": 1,
      "name": "SACS",
      "created_at": "2019-04-14T11:35:24.000Z",
      "updated_at": "2019-04-14T11:35:24.000Z"
    }
  }
]

Is there any common solution for all controllers ? Because the application is already built. Its very hectic now to format data manually in every controller. Thanks in advance.

dimanche 14 avril 2019

vendredi 12 avril 2019

Greatest value from an array of numbers (Ruby)

I am currently learning Ruby and for the sake of my life I cannot find a solution to this:

Return the greatest value from an array of numbers.

Input: [5, 17, -4, 20, 12] Output: 20

Can anyone help me out with this and explain why they used their solution?

thank you.

mercredi 10 avril 2019

Adding max attempt for a single delayed job

I am trying to add max_attempt(if that fails) for a single delayed job

@user.delay(attempts: 2).send_an_email 

and this shows attempts column in delayed job is missing

But could do that for the whole application with adding a delayed_job_config file in the initializer

# config/initializers/delayed_job_config.rb
  Delayed::Worker.max_attempts = 3
  Delayed::Worker.destroy_failed_jobs = false

Is there anyway to add it for single delayed job?

mardi 9 avril 2019

Same ids are assigned again to the new objects after deletion

When I delete a record in my Rails database and create a new one, it gets the id of the deleted record. Is it default Ruby/Rails behaviour? How to avoid this?

lundi 8 avril 2019

Running two server at the same time with a script(Ruby and Rails)

I am new new to Ruby on Rails. In my rails rails application I have used the two servers. One is the rails server and other one is simple ruby server.rb file. I need to start both the server with Start.sh script to deploy.

I have tried the following Code of Start.sh file. But the issue is Rail server is not starting until and unless I stop the ruby server.rb.

start.sh file code

rake ts:stop

rake ts:start

rake ts:index

ruby server.rb

rails server

I want to run both the servers through a single script

Problem with selenium webdriver on linux with ruby

I reinstalled ruby 2.3.1p112, and my spec test do not work. The error was:

Selenium::WebDriver::Error::SessionNotCreatedError: session not created: This version of ChromeDriver only supports Chrome version 74
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Linux 4.15.0-47-generic x86_64)

Can any one help to encode the rails code.I want to share my code in binary executable form?

I want to share my rails code with my client in encoded form so he can not able to read the code.Is it possible in rails

dimanche 7 avril 2019

How to make Rails stop sending Etag header in HTTP Response

I have a ruby on rails application that uses varnish (as a reverse proxy) in front of it. I use apache tomcat as my web server. 80% of requests coming to tomcat via varnish are returning 304 Not Modified, whereas varnish returns 200 OK for these requests.

Upon reading about when the 304 code gets returned, I learnt that, it happens when the request header has "If-None-Match" (whose value is set to ETag header value, previously returned by HTTP response for the same request) or "If-Modified-Since" As my response sizes are very less, I would like my tomcat to skip/ignore these headers and pass the request to my Rails application for handling.

Currently, the time taken by Tomcat to compare the ETags is more than the time taken by my Rails application to respond. Hence, it is not adding any value to my app's performance.

Any help would be greatly appreciated. Thanks in advance!!

jeudi 4 avril 2019

ActiveRecord::RecordNotFound in StaticPagesController#home

I am getting this error whenever I try to access the application. The error is about the application controller. This is the error. Couldn't find all Private::Conversations with 'id': (17, 38) (found 0 results, but was looking for 2).

The error is explained more in the bash as follows ActiveRecord::RecordNotFound (Couldn't find all Private::Conversations with 'id': (17, 38) (found 0 results, but was looking for 2).):

app/controllers/application_controller.rb:28:in `opened_conversations_windows' I have tried changing the find method but things do not seem to work with methods such as find_by.

def opened_conversations_windows


        if logged_in?

            # opened conversations

            session[:private_conversations] ||= []

            @private_conversations_windows = Private::Conversation.includes(:recipient, :messages)
                                              .find(session[:private_conversations])



          else

            @private_conversations_windows = []


        end
end

I expect that when no conversation is found, the app should render nil conversation windows when a user logs in.

Rails Monkey Patch alias_method cause no method error

I am trying to monkey patch rails Rails.cache.fetch/read method, and add my extra log on every fetch/read happened, but i got some other error that i can't google any answer.

here is my monkey patch code

module ActiveSupport
    module Cache
        class Store
            alias_method :old_fetch, :fetch
            alias_method :old_read, :read

            def fetch(name, options=nil)
                Rails.logger.info "Memcached Hotkey Fetching: #{name}"
                Rails.logger.info caller
                old_fetch(name, options)
            end

            def read(name, options=nil)
                Rails.logger.info "Memcached Hotkey Reading: #{name}"
                Rails.logger.info caller
                old_read(name, options)
            end
        end
    end
end

here is where travis busted

class B < ActiveRecord::Base
  def self.cache
    Rails.cache.fetch(CACHE_KEY, :expires_in => 1.hour) do
      all
    end
  end

there is code somewhere callingB.cache.each do |x| blablabla end

Error message:  You have a nil object when you didn't expect it! (NoMethodError),
You might have expected an instance of Array.
The error occurred while evaluating nil.each

the question is what am I doing in wrong way? i just monkey patch two methods under Store, but why it seems overwrite everything that's calling .cache

lundi 1 avril 2019

NoMethodError: undefined method `setup' for Devise:Module

Environment

  • Ruby [1.9.3p547]
  • Rails [3.2.22.5]
  • Devise [3.0.4]

Current behavior

When i try to run any rake or rails command, i am getting below error

rake aborted! NoMethodError: undefined method setup' for Devise:Module /home/tatva/sites/Quotiful-API-master/config/initializers/devise.rb:3:in' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:245:in load' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:245:inblock in load' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:236:in load_dependency' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:245:inload' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/engine.rb:593:in block (2 levels) in <class:Engine>' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/engine.rb:592:ineach' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/engine.rb:592:in block in <class:Engine>' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/initializable.rb:30:ininstance_exec' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/initializable.rb:30:in run' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/initializable.rb:55:inblock in run_initializers' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/initializable.rb:54:in each' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/initializable.rb:54:inrun_initializers' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/application.rb:136:in initialize!' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/railtie/configurable.rb:30:inmethod_missing' /home/tatva/sites/Quotiful-API-master/config/environment.rb:5:in <top (required)>' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:251:inrequire' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:251:in block in require' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:236:inload_dependency' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/activesupport-3.2.22.5/lib/active_support/dependencies.rb:251:in require' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/application.rb:103:inrequire_environment!' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/railties-3.2.22.5/lib/rails/application.rb:305:in block (2 levels) in initialize_tasks' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/gems/rake-12.2.1/exe/rake:27:in' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/bin/ruby_executable_hooks:24:in eval' /home/tatva/.rvm/gems/ruby-1.9.3-p547@quotiful/bin/ruby_executable_hooks:24:in' Tasks: TOP => db:migrate => environment (See full trace by running task with --trace)

Expected behavior

Why i am getting this error. is this version issue of devise? I don't want to upgrade devise version as it will effect whole project.

Please help me to resolve this issue. Thanks in advance.

Legacy rails app fails when it tries to precompile assets in docker container

Moving a legacy rails app (rails 3.2) over to docker. I have it working fine locally with docker-compose. The problem comes when I try to build the container for staging.

The line RUN bin/rake assets:precompile it fails because it is initializing the app on precompile event though I have it set to not initialize.

Any help would be greatly appreciated.

Docker File

FROM ruby:2.3.8

ARG RAILS_SECRET_KEY
ARG RAILS_ENV=staging
ARG GITHUB_REPO_API_TOKEN
ARG POSTGRES_USER
ARG POSTGRES_PASSWORD
ARG POSTGRES_DB
ARG DATABASE_HOST
ARG FOG_PROVIDER
ARG FOG_REGION
ARG ASSET_FOG_DIRECTORY
ARG AWS_ACCESS_KEY_ID
ARG AWS_SECRET_ACCESS_KEY

# Most of these deps are for running JS tests. You can add whatever extra deps your project has (ffmpeg, imagemagick, etc)
RUN apt-get update

RUN apt-get update -yqq && apt-get install -yqq --no-install-recommends \
  nodejs \
  qt5-default \
  libqt5webkit5-dev \
  xvfb \
  postgresql \
  postgresql-contrib \
  imagemagick \
  openjdk-8-jdk

# cache the gemfile seperate
COPY Gemfile* /usr/src/app/

# required at CLI
ENV BUNDLE_GITHUB__COM=${GITHUB_REPO_API_TOKEN}:x-oauth-basic

# You'll need something here. For development, you don't need anything super secret.
ENV SECRET_KEY_BASE=${RAILS_SECRET_KEY}
ENV RAILS_ENV=${RAILS_ENV}

# this tells container to cd into app directory
WORKDIR /usr/src/app

# so we don't have to reinstall all the gems when we add just one when we build a new container
ENV BUNDLE_PATH /gems

RUN bundle install

# copy app dir into /usr/src/app in container
COPY . /usr/src/app/

RUN bin/rake assets:precompile

# for the irritating times the server doesn't clean up when container shutsdown
ENTRYPOINT ["./docker-entrypoint.sh"]

CMD ["bin/rails", "s", "-b", "0.0.0.0"]

staging.rb

# Compress JavaScripts and CSS
  config.assets.compress = true

  config.assets.initialize_on_precompile = false

Why is not showing the order indicator arrow in a ransack sort_link?

When I use for example:

    <%= simple_sort_link(medical_test_orders_meta, :description, {default_order: :desc}) %>

...it shows the order indicator arrow. But when I use:

      <%#= sort_link(medical_test_orders_meta, humanize_attribute(medical_test_order_model, :patient), %i(patient_first_name patient_middle_name patient_last_name), {default_order: :desc}) %>

... it doesn't shows the order indicator arrow. It orders first by the first name, then by the middle name, and finally by the last name.

I have tried with several combinations/variants and so far some of them order but do not show the arrow, and others show it but do not order at all.

I have solved the problem very easily using JavaScript/jQuery (please don't mention that kind of solutions), but I would like to know if there is a better/cleaner way to solve this using: rails and/or passing other kind of parameters to the ransack sort_link, etc, etc. I don't like using all that JavaScript code for just an order indicator arrow but on the other hand I like the perfection at all cost, so... HELP PLEASE!!

Ruby - Code someone explain the following code

I have the following piece of code in a library, Could someone explain what does the code ("#{k}=") means in the following piece of code?

 if respond_to?("#{k}=")
        public_send("#{k}=", v)
      else
        raise UnknownAttributeError.new(self, k)
      end

I understand respond_to is a default function in Ruby but there is no definition/explanation given for this syntax, please help us.

thanks.,
Harry