vendredi 29 juin 2018

No route matches in rails ?customize privilege of Action of controller in rails

I have two model Follow user and Master . Follow user can show , edit

Master can add,edit,show and delete follow user .

i need use authenticate_user! for admin add,edit,show and delete

& use authenticate_user! for followuser ,edit,show

before_action :authenticate_user!, except: [:new, :create,:show ,:edit, :destroy] when create new Follow user occur this error

No route matches {:action=>"edit", :controller=>"folusers", :id=>nil}, missing required keys: [:id]

This my routes routes.rb

resources :folusers resources :masters

Rails not logging unicorn.stderr.log messages to syslog

In my unicorn.rb initialization script I have the following lines:

require "syslog/logger"
logger Syslog::Logger.new("unicorn")

Some things come through from this in my syslog file, for example:

Jun 29 12:09:25 server-name unicorn[13451]: Enqueued Searchkick::ReindexV2Job (Job ID: 26c96f2f-6b68-4def-86d4-e101297cd939) to Sidekiq(searchkick) with arguments: "Shopper", "36479"

However, the messages I would typically find in unicorn.stderr.log, for example when there is an error on unicorn startup, do not come through, no matter wether they are INFO or ERRORS.

I have removed the following line: stderr_path "/home/deploy//shared/log/unicorn.stderr.log" Thinking that all the logs from that file would now be sent to the syslogger but that doesn't seem to be the case. It seems they are either being sent to the wrong place or that the log level is somehow misconfigured.

Thanks in advance for any help!

how to share location automatically in facebook in rails?

i work with tracker app . i have latitude and longitude of user send by sensor.

i need when occur problem share location in your Facebook automatically. can every user can do that .

I explore the Facebook Graph Api Feed Api and do some hit and try but didn't get any success.

Ruby on Rails: Why does my array set contain null, passing my null checker?

I have a code that looks like this:

*movie_requests is a scope

def self.records (producer_id = 0)
  actor_list = Array.new
  movie_requests(producer_id).find_each do |studio|
    actor = studio.actors.pluck(:id).uniq
    if (!actor_list.include? actor) && (!actor.nil?)
      actor_list << actor
    end
  end
  return actor_list
end

Originally in the database, it has these actor ids:

[[12305], [3749], [1263], [], [], [1263], [], [12305], []]

.pluck and .uniq makes redundant ids from each studio distinct however [] still exists:

[[12305], [3749], [1263], []]

Why doesn't my && (!actor.nil?) condition catches the null ids and make it a distinct object?

jeudi 28 juin 2018

how to display json data in chart line using chart kick in rails

i want display json data in chart line using chart kick or any gems . hash example

[{"value"=>568}, {"value"=>576}, {"value"=>580}, {"value"=>588}, 
{"value"=>560}, {"value"=>566}, {"value"=>586}, {"value"=>586}, 
{"value"=>566}, {"value"=>587}, {"value"=>589}]

Javascipt code(JQuery) not display in rails app

i want to display chart in view in rails app. use this link http://jsfiddle.net/zz7pB/ contain chart

in application.html.erb and try it in view

<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

in application.js

//= require_tree 
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require chart   ---> name of controller

chart.js in app -> assets -> javascripts

$(function () {
    $(document).ready(function() {
        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        var chart;
        $('#container').highcharts({
            chart: {
                type: 'line',
                animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,
                events: {
                    load: function() {

                        // set up the updating of the chart each second
                        var series = this.series[0];
                        setInterval(function() {
                            var x = (new Date()).getTime(), // current time
                                y = Math.random();
                            series.addPoint([x, y], true, true);
                        }, 1000);
                    }
                }
            },
            title: {
                text: 'Live random data'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: 'Value'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
                        Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            series: [{
                name: 'Random data',
                data: (function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    for (i = -19; i <= 0; i++) {
                        data.push({
                            x: time + i * 1000,
                            y: Math.random()
                        });
                    }
                    return data;
                })()
            }]
        });
    });

});

in index.html.erb

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

i want display this chart in my app this all information. This live chart

when inspect element display div put not contain chart.

i read this Where should I place my jQuery code in my Ruby on Rails applications? but not solve it

how to get specific data from Json and display in Google map in rails

i connected to DB NOSQL online return json value

for example

{
  "_id"=>"5b2e880c1de0c46b00001dda",
  "gps_lattitude"=>"30.63",
  "gps_longitude"=>"31.09",
  "gps_speed_kph"=>"0.1",
  "gps_heading"=>"129.36",
  "gsm_csecond"=>58,
  "gsm_second"=>46,
  "gsm_minute"=>35,
  "gsm_hour"=>21,
  "gsm_month"=>6,
  "gsm_day"=>20,
  "gsm_year"=>2018,
  "HWID"=>"AC37439773C8",
  "pulse_rate"=>585,
  "recrdID"=>458
}

need display gps_longitude & gps_lattitude to google map

when work with sql database can do it easy but not know how can do it use json

mercredi 27 juin 2018

How to auto Update fields in rails

I have a general settings table, parents table, children table and fundings table. Children table has funding_id. each child can have multiple funding applications. In the funding table there is a field status which can be changed only by admin. Once the admin approves the application, I want the amount requested to be subtracted from the amount_remaining field in the children table.The default amount_remaining is the amount_current_year in the general settings. How can I achieve this. Kindly help me.

Funding table schema

 create_table "fundings", force: :cascade do |t|
    t.string "type_of_activity"
    t.string "season"
    t.text "activity_details"
    t.string "name_of_organisation"
    t.date "activity_start_date"
    t.string "number_of_weeks"
    t.string "days_per_week"
    t.string "hours_per_day"
    t.integer "program_registration_cost"
    t.string "family_contribution"
    t.integer "other_funds"
    t.string "other_fund_provider"
    t.integer "amount_requested"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "child_id"
    t.string "status"
    t.date "date_submitted"
  end

General setting scheme

  create_table "generalsettings", force: :cascade do |t|
    t.integer "amount_current_year"
    t.integer "amount_next_year"
    t.date "current_year"
    t.date "next_year"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

Children table schema

create_table "children", force: :cascade do |t|
    t.string "firstname"
    t.string "lastname"
    t.date "dateofbirth"
    t.string "gender"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "parent_id"
    t.integer "amount_remaining"
  end

_form.html.erb (funding application form)

<div class='row'>
  <div class= 'col-xs-12'>
    <%= form_for([@parent, @child, @funding], :html => {class: "form-horizontal",role: "form"}) do |form| %>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :type_of_activity, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.select :type_of_activity, ['Swimming', 'Soccer', 'Cricket', 'Basket Ball'], required: true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :activity_details, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.text_area :activity_details, required: true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :name_of_organisation, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.select :name_of_organisation, ['BCCI', 'IPL', 'Sahara', 'Not listed'], class: "form-control", autofocus:true, required: true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :activity_start_date, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.date_field :activity_start_date, min: Date.today, required: true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :program_registration_cost, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :program_registration_cost, required: true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :amount_requested, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :amount_requested, required: true %>
        </div>
      </div> 
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :date_submitted, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.date_field :date_submitted, value: Date.today, readonly:true, required: true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :status %>
        </div>

      <% if current_user.admin? %>
        <div class="col-sm-8">
          <%= form.select :status,['Pending', 'Approved', 'Declined'], class: "form-control" %>
        </div>
      <% else %>
        <div class="col-sm-8">
          <%= form.select :status,['Pending', 'Approved', 'Declined'], {class: "form-control"}, {:disabled => true} %>
        </div>
      <% end %>

      </div> 
      <div class="form-group">
        <div class="col-sm-10">
          <%= form.submit "Apply", class: 'btn btn-primary btn-lg' %>
        </div>
      </div>
    </div>
  </div>

    <% end %>

how to use rest-client to display specific data in rails

i connect with api to display specific data but not how to use this rails . not know put code in model or controller

require 'rest-client'
require 'json'

url = 'https://xxxx.restdb.io/rest/data'

headers = 
{
    'content-type': "application/json",
    'x-apikey': "-------",
    'cache-control': "no-cache"
}
req = RestClient.get(url, headers)

we = JSON.parse(req.body)

p we

doesn't run assets precompiled command, in production environment

After run this command RAILS_ENV=production bundle exec rake assets:precompile

show this image error.enter image description here

Finding Compatible Gem Versions for Legacy Rails App

I'm currently maintaining a legacy rails app version 3.0.7 and ruby 1.8.7. What's the best way to find what version of a specific gem is compatible with these ruby/rails versions?

Specific use-case: I've been tasked with integrating the Mailchimp API, and I'm not sure what version of mailchimp-api or gibbon to use

mardi 26 juin 2018

is there a way to apply dry and solid principal

am working on this code to make it shorter so that it could be easier to study or read and I have but advanced to apply the dry and solid principle so could you help me with how to refactor this code to do this if brand.rating = high if price_reference < 15 price_suggestion = (price_reference - product_database.shipping_cost * 0.75) * 1.1 price_original = price_suggestion elsif price_reference < 25 price_suggestion = (price_reference - product_database.shipping_cost * 0.775) * 1.1 price_original = price_suggestion elsif price_reference < 50 price_suggestion = (price_reference - product_database.shipping_cost * 0.8) * 1.1 price_original = price_suggestion elsif price_reference < 75 price_suggestion = (price_reference - product_database.shipping_cost * 0.825) * 1.1 price_original = price_suggestion elsif price_reference < 100 price_suggestion = (price_reference - product_database.shipping_cost * 0.85) * 1.1 price_original = price_suggestion elsif price_reference < 200 price_suggestion = (price_reference - product_database.shipping_cost * 0.875) * 1.1 price_original = price_suggestion elsif price_reference < 400 price_suggestion = (price_reference - product_database.shipping_cost * 0.9) * 1.1 price_original = price_suggestion elsif price_reference < 600 price_suggestion = (price_reference - product_database.shipping_cost * 0.925) * 1.1 price_original = price_suggestion else price_suggestion = (price_reference - product_database.shipping_cost * 0.95) * 1.1 price_original = price_suggestion elsif brand.rating = low if price_reference < 15 price_suggestion = (price_reference - product_database.shipping_cost * 0.75) * 0.9 price_original = price_suggestion elsif price_reference < 25 price_suggestion = (price_reference - product_database.shipping_cost * 0.775) * 0.9 price_original = price_suggestion elsif price_reference < 50 price_suggestion = (price_reference - product_database.shipping_cost * 0.8) * 0.9 price_original = price_suggestion elsif price_reference < 75 price_suggestion = (price_reference - product_database.shipping_cost * 0.825) * 0.9 price_original = price_suggestion elsif price_reference < 100 price_suggestion = (price_reference - product_database.shipping_cost * 0.85) * 0.9 price_original = price_suggestion elsif price_reference < 200 price_suggestion = (price_reference - product_database.shipping_cost * 0.875) * 0.9 price_original = price_suggestion elsif price_reference < 400 price_suggestion = (price_reference - product_database.shipping_cost * 0.9) * 0.9 price_original = price_suggestion elsif price_reference < 600 price_suggestion = (price_reference - product_database.shipping_cost * 0.925) * 0.9 price_original = price_suggestion else price_suggestion = (price_reference - product_database.shipping_cost * 0.95) * 0.9 price_original = price_suggestion else if price_reference < 15 price_suggestion = (price_reference - product_database.shipping_cost * 0.75) * 1 price_original = price_suggestion elsif price_reference < 25 price_suggestion = (price_reference - product_database.shipping_cost * 0.775) * 1 price_original = price_suggestion elsif price_reference < 50 price_suggestion = (price_reference - product_database.shipping_cost * 0.8) * 1 price_original = price_suggestion elsif price_reference < 75 price_suggestion = (price_reference - product_database.shipping_cost * 0.825) * 1 price_original = price_suggestion elsif price_reference < 100 price_suggestion = (price_reference - product_database.shipping_cost * 0.85) * 1 price_original = price_suggestion elsif price_reference < 200 price_suggestion = (price_reference - product_database.shipping_cost * 0.875) * 1 price_original = price_suggestion elsif price_reference < 400 price_suggestion = (price_reference - product_database.shipping_cost * 0.9) * 1 price_original = price_suggestion elsif price_reference < 600 price_suggestion = (price_reference - product_database.shipping_cost * 0.925) * 1 price_original = price_suggestion else price_suggestion = (price_reference - product_database.shipping_cost * 0.95) * 1 price_original = price_suggestion end

How to iterate through a Hash Arary in ruby

Trying to iterate over a array using ruby and it is miserably failing,

My Array
people = [{first_name: "Gary", job_title: "car enthusiast", salary: "14000" },
{first_name: "Claire", job_title: "developer", salary: "15000"},
{first_name: "Clem", job_title: "developer", salary: "12000"}]

How to iterate over the above hash to output only the salary value???

I tried using:

people.each do |i,j,k|
puts "#{i}"
end

The results are as below and is not what i was intending,

{:first_name=>"Gary", :job_title=>"car enthusiast", :salary=>"14000"}
{:first_name=>"Claire", :job_title=>"developer", :salary=>"15000"}
{:first_name=>"Clem", :job_title=>"developer", :salary=>"12000"}

Is there a way to iterate through this array and simply list out only the salary values and not the rest???

Thank you,

My irb code is not running, in Ruby

My irb code is not running, after I type my code, what's next? What keys do I have to press? because it keeps making another blank line.

Code:

2.1.2 :002 > family = [ "Hosea", "jason", "Corey", "Kevin"']

2.1.2 :003'> family.each do | fam|

2.1.2 :004'> puts "#{family} have you ever lie to me."

2.1.2 :005'>  end

2.1.2 :006'> fam = gets.chomp

2.1.2 :007'> if fam == yes

2.1.2 :008'> puts "#{family} I respect that you could look in my eyes and tell me that."

2.1.2 :009'>  else

2.1.2 :010'> puts "#{family} i know you lying now bitch?"

2.1.2 :011'> end

2.1.2 :012'>

How do I run a server on ruby on rails?

I want to link to localserver:3000 on ruby on rails but when I use bundle exec rails server, it just exits and doesn't generate the server.

➜  demo git:(master) ✗ bundle exec rails server
    => Booting Puma
    => Rails 5.2.0 application starting in development
    => Run `rails server -h` for more startup options
    Exiting  

This is my route.rb if it helps!

Rails.application.routes.draw do
root "pages#home"
end

I created a controller called pages and created a view called home. When I first generated the server, I already ended the session so I'm wondering how I can generate the server again so I can see my "home" page.

This is what happens when I try to get the server. Can anyone explain to me what could be wrong? Thank you!

lundi 25 juin 2018

RoR and Filemaker Where condition

Not sure if this is possible, but I am wondering if I can compare two fields in a .where. As I am trying to avoid if statements in this case.

For example: Article.where(clidlive: '*', "#{mod_date} > "#{releae_date})

mod_date is a date field in filemaker releae_date is a date field in filemaker.

I'd really appreciate if you could direct me to the right path, or even this is possible.

Thanks, Rob

dimanche 24 juin 2018

how to create line chart and appear data use kickchart in rails?

I have column called speed in table Speed. I need to create a line chart group by minute (created_at) and point appear speed.

For example p1 (110.4) , p2 (113.5), and more.

There can be many values of speed.

in SpeedController.rb

 def index
    #@speeds = current_master.speed.all

    @spee = Speed.where(id_watch: current_master.id_watch)
    }
  end

in speed.html.erb

This line occur error

<%= line_chart @spee.group_by_minute(:created_at).average(:speed) %>

when write <%= @spee.inspect %> for example

#<ActiveRecord::Relation [#<Speed id: 1, id_watch: "hello@hello.com", speed: 79, created_at: "2018-06-23 08:02:00", updated_at: "2018-06-23 08:02:00", master_id: 1>

want draw like this enter image description here

multi association in rails

I have two model User,Admin every model make login

admin.rb

class Admin < ApplicationRecord
   has_many :user
end 

user.rb

class User < ApplicationRecord
   belongs_to :admin
end 

if already User model can also have many of master

how to add this in models

what use of exclusion and inclusion method in rails?

i read rails doc found exclusion and inclusion method this description

2.4 exclusion

This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.

but not understand use it

2.6 inclusion

same define

Trouble with mysql gem after updating to mysql 8 installation

I recently updated mysql through brew upgrade to the newest version:

$ mysql -V
mysql  Ver 8.0.11 for osx10.13 on x86_64 (Homebrew)

Now my Ruby on Rails mysql connection stopped working.

For compatibility with the production environment I have to use gem 'mysql', '2.8.1' and everything was working perfectly before updating. After updating mysql I get the following error message:

$ rails s
=> Booting WEBrick
=> Rails 3.2.5 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
    SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
    This poses a security threat. It is strongly recommended that you
    provide a secret to prevent exploits that may be possible from crafted
    cookies. This will not be supported in future versions of Rack, and
    future versions will even invalidate your existing user cookies.

    Called from: /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/actionpack-3.2.5/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `initialize'.

Exiting
/Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/mysql_adapter.rb:32:in `mysql_connection': undefined method `init' for Mysql:Class (NoMethodError)
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `send'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `new_connection'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:319:in `checkout_new_connection'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:241:in `checkout'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `loop'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `checkout'
from /Users/MyAccount/.rvm/rubies/ruby-version/lib/ruby/1.8/monitor.rb:242:in `synchronize'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:233:in `checkout'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:96:in `connection'
from /Users/MyAccount/.rvm/rubies/ruby-version/lib/ruby/1.8/monitor.rb:242:in `synchronize'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_specification.rb:168:in `retrieve_connection'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_specification.rb:142:in `connection'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/model_schema.rb:308:in `clear_cache!'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activerecord-3.2.5/lib/active_record/railtie.rb:97:in `_callback_before_13'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/callbacks.rb:418:in `_run__1580337521__prepare__4__callbacks'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/callbacks.rb:405:in `send'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/callbacks.rb:405:in `__run_callback'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/callbacks.rb:385:in `_run_prepare_callbacks'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/callbacks.rb:81:in `send'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/callbacks.rb:81:in `run_callbacks'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/actionpack-3.2.5/lib/action_dispatch/middleware/reloader.rb:74:in `prepare!'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/actionpack-3.2.5/lib/action_dispatch/middleware/reloader.rb:48:in `prepare!'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/application/finisher.rb:47
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/initializable.rb:30:in `instance_exec'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/initializable.rb:30:in `run'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/initializable.rb:55:in `run_initializers'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/initializable.rb:54:in `each'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/initializable.rb:54:in `run_initializers'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/application.rb:136:in `initialize!'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/railtie/configurable.rb:30:in `send'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/railties-3.2.5/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /Users/MyAccount/Development/REPRO/webapp/config/environment.rb:9
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `gem_original_require'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:236:in `load_dependency'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
from /Users/MyAccount/Development/REPRO/webapp/config.ru:3
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/rack-1.4.7/lib/rack/builder.rb:51:in `instance_eval'
from /Users/MyAccount/.rvm/gems/ruby-version@webapp/gems/rack-1.4.7/lib/rack/builder.rb:51:in `initialize'
from /Users/MyAccount/Development/REPRO/webapp/config.ru:0:in `new'
from /Users/MyAccount/Development/REPRO/webapp/config.ru:0

How can I solve this problem? Is there a way to solve the mysql connection?

Unfortunately mysql2 is not an option for the production environment.

how to store json to database in rails

have URl want to store json data to database automatically

site provide this code but use Java

HttpResponse response = Unirest.get("https://xproject.restdb.io/rest/data")
  .header("x-apikey", "42ba8a6dc7532aa8319a58310281665e394e4")
  .header("cache-control", "no-cache")
  .asString(); 

This Example of json

enter image description here

model called speed contain speed & id
need save gps_speed_kph = speed & id_watch ==_id

samedi 23 juin 2018

Rails Active Admin base errors - add direct anchor link to the field with error

I have a very long form inside Rails Active Admin.

I would like to customize the base errors messages, that is to say the errors displayed on top of the page (not the ones on each field), so that instead of just being the default one (see example below), the user could have inside this text a "shortlink", that is to say a link to the field with the error so that he can just click and be transported on the page to the field with the error.

Current error message:

enter image description here

Error message i would like to have

For example the text could read:

 "Images at least one image is required. <a href="#link_to_anchor_of_field_with_error">Please check it</a>.

Note that in my Camping form page, I can edit Camping attributes but also the Rooms (they have a belongs to/has_many relation with Camping model=> one camping has many Rooms) So this should be appliable to both attributes of Camping but also to the attributes of the associated rooms if they turn out to have errors on the form submission

ActiveAdmin.register Camping do

  form do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs "Information for the Camping" do
      f.input :name,        
      f.input :city        
    end

    f.inputs "Rooms" do
      f.has_many :rooms,
                   allow_destroy: true,
                   heading:       false, 
                   new_record:    true,                   
                   sortable_start: 0 do |room|
        room.input :name,          
        room.input :room_nb,         
        room.input :facilities
      end
    end 
  end

I even am not sure if it should be done on config of Active Admin or more inside config of Formtastic, which is the form DSL Active Admin is using. Maybe the customization found in this post (Make semantic_errors render the exact error-message) could be used but it's way beyond my level:)

What is the difference between Api in Controller and another folder in rails?

What is the difference between Api in Controller and another folder in rails ?

class PostsController < ApplicationController 
        def index
            posts = Post.all
            render json: {status: 'SUCCESS', message: 'Loaded all posts', data: posts}, status: :ok
        end 
end

and use Api version

-Controller |
             -- api|
                    --v1

and which best or use it

json vs html in rails

have some question when generate controller appear some comment

i want to know use importance with these line

# GET /folusers # GET /folusers.json def index

first question rails generate json file. can use instead of api version .

# POST /folusers # POST /folusers.json def create

second question how access create method by json


final question need to create mobile app and connect with db are enough use generate in controller or use api version ?

how to change git folder from previous to new?

Having problem in using the same repository previously used

I was trying some new stuff with my rails project and ended up losing its major functionalities, but I git my project on GitHub. So i downloaded from there and now when I made some changes to this newly downloaded file, I cant git to same repo now. How to git into that same repository. Like it has 8 commits now and now if I do my another commit it should be the 9th. Any help?

Hope the problem is clear..

vendredi 22 juin 2018

How can I make Regular expression for decimal

How can I make Regular expression for decimal(9,6) ? wanna validate in Rails program. please help me.

Sidekiq Gem with Ruby 1.9.3

Ruby version: 1.9.3

Rails Version: 3.2.22

I have been using delayed_job_active_record gem since 2014 and now the application has to run lots of background jobs so decided to use sidekiq. I was trying to install sidekiq 4.0.0 and 'redis', '~> 3.0', '>= 3.0.6', when i am doing the bundle i am getting this error:

enter image description here

I also have tried some other version but still i am getting this error, also i would like to know which is the compatible version of sidekiq which i can use it with ruby 1.9.3?

Also i would like to know is there any other gem versions do we need to consider like redis....?

Set default value with grouped_options_for_select , using f.select

I have a grouped drop down menu rendered by the following,

      = f.select :location_id, grouped_options_for_select(grouped_location_options, default_location_name), { selected: default_location_name }, class: 'form-control'

I would like to have the default value to be Unassigned, but the above code doesn't seem to be doing what I'd like.

Could someone give me some clues to solve this??

Many thanks in advance!

jeudi 21 juin 2018

Decimal issue in ruby on rails

I stored a decimal value 0.57 as number (10,2) in the database. When i retrieve the value on my screen using ruby on rails it shows 0.570000000001 please help

How to deploy rails via Capistrano and Jenkins using GitHub

I am new to Jenkin and I need to deploy rails application with jenkin. I am using capistrano task to deploy rails application to ec2 server.

Our devops teams are maintaining the jenkin server and they creted a credential to fetch the latest repo from github. I am not sure if I have to use their credential or not or if yes how can I use their credential

deploy@localhost:~/rails_project (staging)$ bundle exec cap staging deploy
* executing `staging'
  triggering start callbacks for `deploy'
* executing `multistage:ensure'
* executing `deploy'
* executing `deploy:update'
** transaction: start
* executing `deploy:update_code'
  updating the cached checkout on all servers
  executing locally: "git ls-remote git@github.com:Private-Repo/rails_project.git staging"
  command finished in 4387ms
* executing "if [ -d /home/ec2-user/rails_project/shared/cached-copy ]; then cd /home/ec2-user/rails_project/shared/cached-copy && git fetch -q origin && git fetch --tags -q origin && git reset -q --hard 2349f182417bc5932c7cdefcfeecac12b98ade28 && git clean -q -d -x -f; else git clone -q git@github.com:Private-Repo/rails_project.git /home/ec2-user/rails_project/shared/cached-copy && cd /home/ec2-user/rails_project/shared/cached-copy && git checkout -q -b deploy 2349f182417bc5932c7cdefcfeecac12b98ade28; fi"
servers: ["111.111.111.111"]
* establishing connection to gateway `"bastion_user@bastion.server.com"'
* Creating gateway using bastion_user@bastion.server.com
* establishing connection to `111.111.111.111' via gateway
[111.111.111.111] executing command
** [111.111.111.111 :: out] Failed to add the RSA host key for IP address '192.xx.xxx.xxx' to the list of known hosts (/home/ec2-user/.ssh/known_hosts).
** [111.111.111.111 :: out] Permission denied (publickey).
** [111.111.111.111 :: out] fatal: Could not read from remote repository.
** 
** Please make sure you have the correct access rights
** and the repository exists.
command finished in 1925ms
*** [deploy:update_code] rolling back
* executing "rm -rf /home/ec2-user/rails_project/releases/20180621070926; true"
servers: ["111.111.111.111"]
[111.111.111.111] executing command
command finished in 1422ms
failed: "env RAILS_ENV=staging sh -c 'if [ -d /home/ec2-user/rails_project/shared/cached-copy ]; then cd /home/ec2-user/rails_project/shared/cached-copy && git fetch -q origin && git fetch --tags -q origin && git reset -q --hard 2349f182417bc5932c7cdefcfeecac12b98ade28 && git clean -q -d -x -f; else git clone -q git@github.com:Private-Repo/rails_project.git /home/ec2-user/rails_project/shared/cached-copy && cd /home/ec2-user/rails_project/shared/cached-copy && git checkout -q -b deploy 2349f182417bc5932c7cdefcfeecac12b98ade28; fi'" on 111.111.111.111

But jenkin is using a credential and it can fetch repo grom github, how can I use github, capistrano and jenkin with github key together. If more information needed please do ask, Thanks

mercredi 20 juin 2018

Form submit creates GET call instead of POST call in Ruby on mobile view

I have searched through various answers but none have worked for me so far. So here is my form which is working fine when I do a form submission from web view, but on mobile the form automatically does a GET call instead of POST call. However when I remove, target: :_blank, it works fine on mobile. But I need to redirect user to a new page as I change URLs when search button is clicked.

Current url: http://localhost:4000/hotels/470?website_template_id=3

NewPage url: http://localhost:4000//booking_widget/availability

The same URLs are working fine on web though.

<div class="booking-widget">
  <%= form_tag("#{Settings.host_url}/booking_widget/availability", method: :post , target: :_blank , id: :booking_search_form,:class => "form-inline reservation-horizontal clearfix")%>
    <div class="booking-area">
      <div class="booking-values">
        <h4>CHECK IN</h4>
        <input type="hidden" id="check-in" name="start_date" value="" />
        <p class="check-in"> <span><span></p>
        <div id="from"></div>
      </div>
      <div class="booking-values">
        <h4>CHECK OUT</h4>
        <input type="hidden" id="check-out" name="end_date" value="" />
        <p class="check-out"> <span><span></p>
        <div id="to"></div>
      </div>
      <div class="booking-values">
        <input type="hidden" id="rooms" name="rooms" value="1" />
        <h4>ROOMS</h4>
        <p class="rooms">1</p>
        <div class="dropdown">
          <ul id="booking_room_select">
            <%(1..@max_no_of_rooms).each do |num|%>
            <li data-value="<%=num%>"><%=num%></li>
            <%end%>
          </ul>
        </div>
      </div>
      <div class="booking-values">
        <input type="hidden" id="adults" name="adults" value="1" />
        <h4>ADULTS</h4>
        <p class="adults-click">1</p>
        <div class="adults-children">
          <div class="room-set">
            <div class="room-header">
              ROOM 1
            </div>
            <div class="room-changer">
              <div class="changers adults">
                <p>ADULTS</p>
                <input id="single_room_no_of_adults" class="form-control numbers-count" type="number" value="1" min="1" max="<%=@max_no_of_adults%>" disabled />
              </div>
              <div class="changers children">
                <p>CHILDREN</p>
                <input id="single_room_no_of_children" class="form-control numbers-count" type="number" value="0" min="0" max="<%=@max_no_of_children%>" disabled />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="booking-values">
        <input type="hidden" id="children" name="children" value="0" />
        <h4>CHILDREN</h4>
        <p class="children-click">0</p>
      </div>
      <div class="booking-values hidden">
        <input type="hidden" name="hotel_id" value="<%=@hotel.id%>"/>
        <input type="hidden" name="currency" value="INR"/>
        <input type="hidden" name="party" id="party" value=""/>
        <input type="hidden" id="website_template_id" name="website_template_id" value="3" />
      </div>
    </div>
    <div class="booking-cta">
      <button id="booking-widget-submit" formmethod="post" type="submit">BOOK NOW</button>
    </div>
  </form>
  <div class="clearfix"></div>
</div>

My route is defined as:

post 'booking_widget/availability' => 'booking_widget#availability', :as => 'booking_availability'

How to include static files within files

How can we include static files in a ruby file from a directory.

I have a ruby file where I am trying to include static content from all files of .conf extension in a local directory.

I tried using include=/tmp/config.d/*.conf but that did not work.

mardi 19 juin 2018

i want to verify if an email existe in database of the website or no

i want to verify if the email i am using exist in website or no so i post the email with random password then from the code source using searching method i want to see if string "email invalid" or whatever exist in source code or not if it exist then its invalid if not then it's valid email and it exist in database of the website i tried this

require 'net/http'`
require 'uri'`
require 'json'`

uri = URI.parse("https://www.facebook.com")
header = {'Content-Type': 'text/json'}
user = {user: {
               email: 'chahin1@gmail.com',
               password: 'mterm581998'
                  }
        }
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json
response = http.request(request)
puts response
puts request.body
source = Net::HTTP.get(uri)
puts source

Don't find how to link to user_post

I'm new on rails, I work on a application. My user can create a post, posts belong to user. On my index user I want to link_to the user_post for each user, I try a lot of solution, but nothing work...

_list.html.erb :

<div id="filterrific_results">

<div>
  <%= page_entries_info users %>
</div>

<% @users.each do |user| %>
  <% if user.coach? %>
    <h1><%= user.fname %> <%= user.lname %></h1>
    <h2><%= user.mother_tongue %></h2>
      <center>
        <p><%= user.postal_code %> <%= user.locality %></p>

        <p><%= link_to "En savoir plus", **user_post_path** %></p>
      </center>
  <% end %>
<% end %>
</div>


<%= will_paginate users %>

How do I run Rspec code for a simple update code?

How do I run Rspec code for simple update code. Here is a code in my controller

def update
  respond_to do |format|
    if @question.update(question_params)
      format.html { redirect_to @question, notice: t('.question_update') }
    else
      format.html { render :edit }
    end
  end
end

I am trying for too long. Can anyone help!!!!

Active Record Query don't load all id's

I have an active record query like this one:

House.where.not(id: Person.ill.pluck(:house_id))

When I run explain on this query, I see that all the id's get loaded into the query:

Seq Scan on houses  (cost=0.00..4274.07 rows=1102 width=77)
 Filter: id <> ALL ('{1117,487,842,126,127,459,458,515,332,55,54,10,1697,449,448,1555,13,510,1986,8,9,7,6,5,1865,519,157,513,512,56,103,28,27,97,25,23,385,138,278,92,1,435,196,195,61,363,229,230,238,237,231,160,158,749,748,518,517,174,173,172,395,153,1170,207,206,276,199,198, ....

Is there a more performent method to achieve the same query? Without loading all the ids?

specific association two model contain same name

I have two model user & speed . user has many speed

user contain username, email, password, nameofwatch

speed contain nameofwatch, speed, userid

can associate between two model by nameofwatch.

if nameofwatch in user = nameofwatch in speed

appear current_user value of speed

lundi 18 juin 2018

Common arguments graphQL

I'm trying to implement two mutations in graphql-ruby - one for creation of a resource, and one for editing. In most scenarios, they both take the exact same parameters from the client, so I want to avoid duplicating the mutations and try and have the arguments specified in a reusable class/module.

I'm using graphql-ruby 1.8 and the new class based API, and have started with this:

class Mutations::ApplicationMutation < GraphQL::Schema::Mutation
  ... common to every mutation ...
end

class Mutations::CreateResourceMutation < Mutations::ApplicationMutation
  argument :name, String, required: true
  argument :description, String
  argument :create_only_field, String
end

class Mutations::UpdateResourceMutation < Mutations::ApplicationMutation
  argument :name, String, required: true
  argument :description, String
  argument :update_only_field, String
end

In this basic example, the name and description attributes are the same in both mutations. I've extracted the resolver out into another class so that is reusable, but I'm not sure the best way to tackle the arguments.

I imagine an ActiveSupport::Concern would work, but it doesn't feel right or the way I think it should work for this, but I'm very new to GraphQL in general so have no idea.

How to fix this error in rails

rails testcase was not working. when i was run my test shows the following error.

validate_ruby!': Your Ruby version is 2.3.3, but your Gemfile specified 2.4.2 (Bundler::RubyVersionMismatch)

Rails: Select items from a db and insert them into another db (2 different controllers)

I have a list displayed from a model distrib. And I would like the user to be able to select items in the list and add all of them to a table called listdedistribution (sorry for the frenglish). I manage to get the check-box displayed but I get stucked there. I would also like to paginate if that is possible, without forgetting the selection from the first page. My distrib/index.html.erb :

<%= form_tag listdedistributions_path %>
    <table class="table table-hover">
      <thead>
      <th scope="col"> Id</th>
      <th scope="col"> First Name</th>
      <th scope="col"> Last Name</th>
      <th scope="col"> Email</th>
      <th scope="col"> Company</th>
      <th scope="col"> Select</th>
      <th scope="col"> Ind. Delete</th>

      </thead>
      <% @distribs.each do |distrib| %>
        <tbody>
        <tr>
          <th scope="row">   <%= distrib.id %> </th>
          <td>    <%= best_in_place distrib, :first_name %>
          </td>
          <td>    <%= best_in_place distrib, :last_name %>
          </td>
          <td>    <%= best_in_place distrib, :email %>
          </td>
          <td>    <%= best_in_place distrib, :company %>
          </td>
          <td>
            <%= check_box("distribs_selected", "selected_distribs[]", {multiple: true}, distrib.id, nil) %>
          </td>
          <td>
            <%= link_to (t :Delete), distrib_path(distrib), method: :delete, data: {confim: "You will be deleting this item, Are you sure ?"}, class: "btn btn-default" %>
          </td>
        </tr>
        </tbody>
      <% end %>
    </table>
    <%= submit_tag "Add to mailist" %>
  </div>

My controller for distrib:

class DistribsController < ApplicationController

  before_action :find_distrib, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]
  before_action :authenticate_user!
  respond_to :html, :json

  def index
    @distribs = Distrib.all.order("created_at DESC")
  end
  def show
    @distribs = Distrib.all.order("created_at DESC")
  end
  def new
    @distrib = current_user.distribs.build
  end
  def edit
  end
  def destroy
    @distrib = Distrib.find params[:id]
    if @distrib.present?
      RemovedContact.create(:email => @distrib.email, :user_id => @distrib.user_id, :first_name => @distrib.first_name, :last_name => @distrib.last_name, :company => @distrib.company,)
      @distrib.delete
      redirect_to distribs_path
    else
      redirect_to distribs_path
    end
  end
  def distrib_params
    params.require(:distrib).permit(:first_name, :last_name, :email, :user_id, :telephone, :company, :address, :city, :country, :memo, :location_met)
  end
  def update
    @distrib = Distrib.find params[:id]
    respond_to do |format|
      if @distrib.update(distrib_params)
        format.html {redirect_to(@distrib, :notice => 'Updated was successfull.')}
        format.json {respond_with_bip(@distrib)}
      else
        format.html {render :action => "edit"}
        format.json {respond_with_bip(@distrib)}
      end
    end
  end
  def create
    @distrib = current_user.distribs.build(distrib_params)
    if @distrib.save
      redirect_to distribs_path
    else
      render 'new'
    end
  end
  def listdedistribution
    @listdedistribution = current_user.listdedistributions.build
  end
  def find_distrib
    @distrib = Distrib.find(params[:id])
  end
  def make_inactive
    @distrib = Distrib.find params[:id]
    @distrib.update_columns(activecontact: "1")
  end
  def make_active
    @distrib = Distrib.find params[:id]
    @distrib.update_columns(activecontact: "0")
  end
end

My Listdedistrution controller

class ListdedistributionsController < ApplicationController
  before_action :find_listdedistribution, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]
  before_action :authenticate_user!


  def index
    @listdedistributions = Listdedistribution.all.order("created_at DESC")
  end

  def show
    @listdedistributions = Listdedistribution.all.order("created_at DESC")
  end

  def new
    @listdedistribution = current_user.listdedistributions.build
  end


  def edit
  end

  def destroy
    @listdedistribution.destroy
    redirect_to listdedistributions_path
  end

  def update
    if @listdedistribution.update(listdedistribution_params)
      redirect_to listdedistributions_path(@listdedistribution)
    else
      render 'edit'
    end
  end

  def create
    @listdedistribution = current_user.listdedistributions.build(listdedistribution_params)

    if @listdedistribution.save

      redirect_to listdedistributions_path
    else
      render 'new'
    end
  end

  def listdedistribution_params
    params.require(:listdedistribution).permit(:distrib_id, :name, :user_id, :group_id)
  end

  def find_listdedistribution
    @listdedistribution = Listdedistribution.find(params[:id])
  end

  def find_sender
    @listdedistribution = Listdedistribution.find(params[:user_id.email])
  end

  def find_entreprise
    @listdedistribution = Listdedistribution.find(params[:entreprise_id])
  end
end

my Listdedistribution schema looks like:

  create_table "listdedistributions", force: :cascade do |t|
    t.integer "distrib_id"
    t.integer "user_id"
    t.integer "group_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

I do not think that it is complex, but do not have an idea of how to head next. Can someone help please? Thank you

This is my user controller. How to test this code in RSpec?

How to write test case in this user log in. i am newbie in rails testing i am using Rspec gem. i need any tutorial for rails test.

if params.key?(:mobile) && params.key?(:password)
  user = User.find_by(mobile: params[:mobile], is_active: 1)
  if user.nil?
    output = { status: '06', message: 'Invalid user.' }.to_json
  elsif user.authenticate(params[:password])
    auth_token = JsonWebToken.encode(id: user.id,
                                     user_type: user.user_type)
    object = { id: user.id, user_type: user.user_type,
               name: user.name }
    output = { status: '10', message: 'Successful.',
               auth_token: auth_token, user: object}.to_json
  else
    output = { status: '06', message: 'Incorrect password.' }.to_json                         
  end
else
  output = { status: '01', message: 'Invalid parameters.' }.to_json
end

render json: output, status: :ok

samedi 16 juin 2018

Changing Column name in SQLite Database

I created a wrong column name in my reservations table by typing this in the terminal:

rails g model Reservation room:references

BUT i now want the column name change from room_id to wall_id

I tried to run this in my terminal:

rails g migration change_column_name

In the then created file i typed:

class ChangeColumnName < ActiveRecord::Migration[5.1]
def change
rename_column :reservations, :room, :wall
end
end

But after i run rails db:migrate this shows up in the Terminal:

rails aborted! StandardError: An error has occurred, this and all later migrations canceled: No such column: reservations.room

What am i doing wrong in the changing process?

vendredi 15 juin 2018

rails and rake commands freeze/hang

I've recently updated an old application to from 3.2.13 to 4.2.10. I've got the application running in development mode but any rake or rails commands I try to run just hang/freeze. The terminal window will hang for a second and then nothing, I'm unable to even stop the process with ctrl-c. I've read a lot about running 'spring stop' to fix this but I don't have spring installed on this app.

Running the commands with --trace aren't particularly helpful. rails generate model Foo --trace gives me nothing and rake db:migrate --trace gives me: ** Invoke db:load_config (first_time) ** Execute db:load_config ** Execute db:migrate before freezing. Any pointers in the right direction would be appreciated.

Rails foreign key optional don't work

I have troubles in my rails API with a model, my plays_cards model have some foreigns keys but with one I have troubles because I got Mysql2::Error: Field 'deck_id' doesn't have a default value but I don't need my deck and game to be obligatory.

PS: it works in development but not in production

This is my model:

class PlayCard < ApplicationRecord

# @!group RELATIONS
belongs_to :card
belongs_to :deck, optional: true
belongs_to :game, optional: true
belongs_to :user
# @!endgroup

# @!group VALIDATORS
validates :card_id, presence: true, blank: false, nill: false
validates :user_id, presence: true, blank: false, nill: false
validates :atk, presence: true, blank: false, nill: false, numericality: { greater_than_or_equal_to: 0 }
validates :hp, presence: true, blank: false, nill: false, numericality: { greater_than: 0 }
validates :uid, presence: true, allow_blank: false, allow_nil: false, length: { is: 4 }, uniqueness: true
# @!endgroup
end

And this is my migration:

class CreatePlayCards < ActiveRecord::Migration[5.2]
def change
create_table :play_cards do |t|
  t.references :card, foreign_key: true, null: false
  t.integer :atk, null: false
  t.integer :hp, null: false
  t.references :deck, foreign_key: true
  t.references :game, foreign_key: true
  t.string :uid, limit: 4, null: false

  t.timestamps
end
end
end

Do you have an idea ?

Have a nice day

Multiple Select select_tag in mobile populated options disappears when touched

.left.gap_right
  %label.select.control-label{:for => "appointment_reason_ids"} Reasons
  = select_tag("appointment[reason_ids][]", 
  options_for_select(Reason.option_list, f.object.reason_ids),  {:class => 
  'span5 multiselect', :multiple => :multiple})

I am using the multi-select feature in rails 3. The above code works fine on Laptop, but when used in mobile the populated options closes on touch. Is there any solution for this. Or any alternative way of using this.

jeudi 14 juin 2018

Ruby on Rails - Import Data from uncommon formatted CSV

I've got CSV files in the following format;

Category-1-GUID,Product1
,Product2
,Product3
Category-2-GUID,Product4
,Product5

and the task should write following data to the model:

Category-1-GUID,Product1
Category-1-GUID,Product2
Category-1-GUID,Product3
Category-2-GUID,Product4
Category-2-GUID,Product5

I've found Ruby on Rails - Import Data from a CSV file very useful to import the data but this little variance makes me became a blockhead....

Thanks in Advance! Best regards

mercredi 13 juin 2018

wrong number of arguments (given 1, expected 0)

I want to upload photos to my website. After i selected the photos and click on "Add Photos" this error comes up. Any ideas how i can solve this?enter image description here

photos_controller.rb

class PhotosController < ApplicationController

def create
@wall = Wall.find(params[:wall_id])

if params [:images]
  params[:images].each do |img|
    @wall.photos.create(image: img)
  end

  @photos = @wall.photos
  redirect_back(fallback_location: request.referer, notice: "Saved...")

 end

end
end

walls.controller.rb

class WallsController < ApplicationController
  before_action :set_wall, except: [:index, :new, :create]
  before_action :authenticate_user!, except: [:show]
  before_action :is_authorised, only: [:listing, :pricing, :description, :photo_upload, :location, :update]

  def index
    @walls = current_user.walls
  end

  def new
    @wall = current_user.walls.build
  end

  def create
    @wall = current_user.walls.build(wall_params)
    if @wall.save
      redirect_to listing_wall_path(@wall), notice: "Saved..."
    else
      fash[:alert] = "Something went wrong..."
      render :new
    end
  end


  def photo_upload
    @photos = @wall.photos
  end

  def location
  end

  def update
    if @wall.update(wall_params)
      flash[:notice] = "Saved..."
    else
      flash[:notice] = "Something went wrong..."
    end
    redirect_back(fallback_location: request.referer)
  end

  private

    def set_wall
      @wall = Wall.find(params[:id])
    end

    def is_authorised
      redirect_to root_path, alert: "You don't have permission" unless current_user.id == @wall.user_id
    end

    def wall_params
      params.require(:wall).permit(:size_sqm, :visibility, :traffic, :wall_name, :summary, :address, :price)
    end

end

Ruby on Rails in the context of TDD

This is a toughie. As an absolute beginner, It's just an overhead.

Should a beginner learn Ruby on Rails in the context of test-driven development?

mardi 12 juin 2018

My Filterrific filter don't work

I try to implement Filterrific on my application to filter Users. I need to filter by mother_tongue, locality and availability start_time. But it doesn't work. There is no errors but there is no filtering...

Model user.rb :

  filterrific(
default_filter_params: {},
available_filters: [
  :search_query,
  :search_query,
  :with_start_time_gte
]
)

scope :search_query, lambda { |query|
return nil  if query.blank?

terms = query.downcase.split(/\s+/)

terms = terms.map { |e|
  (e.gsub('*', '%') + '%').gsub(/%+/, '%')
}
num_or_conditions = 2
where(
    terms.map {
      or_clauses = [
          "LOWER(users.mother_tongue) LIKE ?",
          "LOWER(users.locality) LIKE ?"
      ].join(' OR ')
      "(#{ or_clauses })"
    }.join(' AND '),
    *terms.map { |e| [e] * num_or_conditions }.flatten
)
}
scope :with_start_time_gte, lambda { |ref_date|
where('availability.start_time >= ?', ref_date)
}

Users_controller.rb :

 def index
@filterrific = initialize_filterrific(
  User,
  params[:filterrific]
  #persistence_id: 'shared_key',
  #default_filter_params: {},
  #available_filters: [],
) or return
@users = @filterrific.find.page(params[:page])

# Respond to html for initial page load and to js for AJAX filter updates.
respond_to do |format|
  format.html
  format.js
end

rescue ActiveRecord::RecordNotFound => e
  # There is an issue with the persisted param_set. Reset it.
  puts "Had to reset filterrific params: #{ e.message }"
  redirect_to(reset_filterrific_url(format: :html)) and return
end

index.html.erb :

<% provide(:title, 'Liste des utilisateurs') %>
<h1>Liste des utilisateurs :</h1>

<%= form_for_filterrific @filterrific, html: { id: 'filterrific-no-ajax-auto-submit' } do |f| %>
<div>
  Langue :
  <%= f.text_field(
  :search_query,
  class: 'mother_tongue filterrific-periodically-observed'
) %>
</div>
<div>
  Ville :
    <%= f.text_field(
  :search_query,
  class: 'locality filterrific-periodically-observed'
) %>
</div>
<div>
  Date de départ :
    <%= f.text_field(:with_start_time_gte, class: 'js-datepicker') %>
</div>

<%= f.submit 'Rechercher' %>

<div>
  <%= link_to(
   'Reset filters',
  reset_filterrific_url,
) %>
</div>

<%= render_filterrific_spinner %>

_list.html.erb :

<div id="filterrific_results">

<div>
<%= page_entries_info users %>
</div>

<% @users.each do |user| %>
  <h1><%= user.fname %> <%= user.lname %></h1>
    <h2><%= user.mother_tongue %></h2>
  <center>
    <p><%= user.postal_code %> <%= user.locality %></p>

    <p><%= link_to "En savoir plus", user_path(user) %></p>
  </center>
<% end %>

I'm new on rails, so thank you for your help.

Rails 3 Update large amount of data

I want to update a large amount of data, but how I do it now it will take ages to finish. Is there a quicker way?

What I have now is:

class User < ActiveRecord::Base
    has_many :posts
    has_many :articles, through: :posts
end


class Post < ActiveRecord::Base
    belongs_to :user
    has_many :articles
end


class Article < ActiveRecord::Base
    belongs_to :post
end

Now I want to add the User directly to the articles. I added the column user_id to the article model and now I want to add the user_id to all articles. I use the following code:

Article.all.each do |article| 
    article.user_id = article.post.user_id
    article.save!
end

But this takes ages with the 20 million articles I have.

Do you have an idea how I can update the user_id to the Article model quicker?

jeudi 7 juin 2018

Left outer join rails with eager loading on where condition

I got a system down issue while eager loading records with where condition.

I've read a blog on link. It spokes about the performance issue while using where condition with eager loading associations.

@customers = Customer.all.includes(:invoices, :receipts).where(invoices: { status: "open" })

"This generates two left outer joins. Whats going to happen is that the database is going to return a row for every unique combination of customer, invoice and receipt. So if we have 25 customers, each customer has 10 invoices (250 total) and 10 receipts (250 total). The result set that is returned is not 525 records, but something closer to 2500 records. Now Rails has to instantiate all of that into ActiveRecord objects."

I am not getting how come it generates 2500 records?

mercredi 6 juin 2018

Can't start up a 'thin' server in Rails; 'listening on http://0.0.0.0:3000/' gives error page

I'm not sure how to debug this: if I run the regular rails server with rails s, I get an SSL Protocol error on localhost, and if I run thin start --ssl, I get an empty response.

Ideally I'd like to start a server with https:// so I can use Omniauth with a bunch of websites like Facebook.

Rails rendering why have to call .to_json

I work on a Rails API, and I want to render some binary in json. To do that I convert my binary in hex to render it.

So I have

#<PlayCard id: 3, card_id: 12, atk: 10, hp: 9, deck_id: nil, game_id: nil, uid: ".dk\x8A", created_at: "2018-06-06 15:17:25", updated_at: "2018-06-06 15:17:25", user_id: 27>
(byebug) play_card.to_json
{"id"=>3, "card_id"=>12, "atk"=>10, "hp"=>9, "deck_id"=>nil, "game_id"=>nil, "uid"=>"2e646b8a", "created_at"=>Wed, 06 Jun 2018 17:17:25 CEST +02:00, "updated_at"=>Wed, 06 Jun 2018 17:17:25 CEST +02:00, "user_id"=>27}

My question is about the rendering of my object. With my method show I Have no problem but with my method create I have to call my_object.to_json did you have an idea ? With out the .to_json I have a ActionDispatch::TestResponse object.

def show
  record = PlayCard.find_by(id: params[:id])
  if record.present?
    render json: record.attributes.except('uid'), status: :ok
  else
    render json: {}, status: :no_content
  end
end

def create
  play_card = PlayCardsService.create(play_card_params)
  if play_card.valid?
    render json: play_card.to_json, status: :created
  else
    render json: { status: 'KO', errors: play_card.errors.full_messages }, status: :unprocessable_entity
  end
end

class PlayCardsService

  class << self

    def create(play_card_params)
      PlayCard.create(play_card_params)
    end

  end

end

def to_json(options = {})
  bin = bin_to_hex(self.uid)
  self.uid = nil
  json = self.as_json
  json['uid'] = bin
  json
end

def bin_to_hex(s)
  s.each_byte.map { |b| b.to_s(16).rjust(2,'0') }.join
end

Thanks for your help

Have a nice day,

mardi 5 juin 2018

How Implement filters on my users index?

I work on an application and I try to implement a filter for my users index. I try a lot of solutions on the web but not successfully. I need to filter with mother_tongue, locality, and after availability (with a calendar).

I first try with a simple search form solution, but I think it's not the best solution, so I try with Justin Weiss solution but it didn't work, so I try to put my own filters in my user model but it's unsuccessfully :

model :

include Filterable

def self.apply_filters(params)
user = self
user = user_by_mother_tongue(mother_tongue: params[:mother_tongue]) if params[:mother_tongue].present?
user = user_by_locality(locality: params[:locality]) if params[:locality].present?
user
end

Being blocked, so I decided to prioprise on the filters mother_tongue and locality and keep filter calendar for later, however I can not find a way out ...

my users controller :

before :

def index
 @users = User.where(activated: true).paginate(page: params[:page])
end

after :

  def index
   @users = User.filter(params.slice(:mother_tongue, :locality))
  end

index.html.erb :

<% provide(:title, 'Liste des utilisateurs') %>
<h1>Liste des utilisateurs :</h1>

<%= form_tag(users_path, method: :get) do %>
 <%= label_tag :mother_tongue, "Langue :" %>
 <%= text_field_tag :mother_tongue, params[:mother_tongue] %>

 <%= label_tag :locality, "Ville :" %>
 <%= text_field_tag :locality, params[:locality] %>

 <%= submit_tag 'Search', name: nil %>
<% end %>

<table>
 <thead>
   <tr>
    <th></th>
   </tr>
 </thead>

 <tbody>
  <tr>
    <% for user in @users %>
      <div class='user'>
        <strong> <%= user.fname %> </strong>
      </div>
       <%= link_to 'Savoir plus', user_path(user) %>
    <% end %>
  </tr>       
</tbody>

models/concern/filterable.rb :

module Filterable
  extend ActiveSupport::Concern

  module ClassMethods
    def filter(filtering_params)
      results = self.where(nil)
        filtering_params.each do |key, value|
          results = results.public_send(key, value) if value.present?
        end
      results
    end
  end
end

Thanks in advance for your help !

How to shuffle n elements in array in rails?

Let

example = [1,2,3,4,5,6,7,8,9]

Want to shuffle first 5 elements. Other elements have to remains in same index, e.g.:

[2,4,1,3,5,6,7,8,9]
[3,1,4,5,2,6,7,8,9]
# etc

samedi 2 juin 2018

wicked_pdf not working in production server

Locally It works without any error but when I try to generate the PDF on the server it trows:

RuntimeError (Failed to execute: ["/usr/local/bin/wkhtmltopdf", "-q", "file:////tmp/wicked_pdf20180531-994-1x8fbfn.html", "/tmp/wicked_pdf_generated_file20180531-994-1vidmtk.pdf"] Error: PDF could not be generated!

Command Error: /usr/bin/env: ruby: No such file or directory ):

Here's what's on my_controller.

pdf=WickedPdf.new.pdf_from_string(render_to_string('disc_bill',:layout=>false))
  save_file = Rails.root.join("public","bill.pdf")
  File.open(save_file, 'wb') do |file|
    file << pdf
  end

And in my Gemfile

gem 'wicked_pdf', '~> 1.1' gem 'wkhtmltopdf-binary', '~> 0.12.3.1'

vendredi 1 juin 2018

Error from inside ActionView::Template::Error - String can't be coerced into Integer

We recently updated the ruby and rubygems versions of our app, and we've been consistently getting the following error:

A TypeError occurred in [model]#[view]:

String can't be coerced into Integer
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_view/template/error.rb:92:in `+'

Here is the backtrace:

vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_view/template/error.rb:92:in `+'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_view/template/error.rb:92:in `sum'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_view/template/error.rb:92:in `source_extract'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_view/template/error.rb:112:in `annoted_source_code'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_dispatch/middleware/debug_exceptions.rb:68:in `block in log_error'
vendor/bundle/ruby/2.5.0/gems/activesupport-3.2.22.5/lib/active_support/deprecation/reporting.rb:20:in `silence'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_dispatch/middleware/debug_exceptions.rb:66:in `log_error'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_dispatch/middleware/debug_exceptions.rb:34:in `render_exception'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_dispatch/middleware/debug_exceptions.rb:27:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/exception_notification-4.1.1/lib/exception_notification/rack.rb:32:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/railties-3.2.22.5/lib/rails/rack/logger.rb:32:in `call_app'
vendor/bundle/ruby/2.5.0/gems/railties-3.2.22.5/lib/rails/rack/logger.rb:16:in `block in call'
vendor/bundle/ruby/2.5.0/gems/activesupport-3.2.22.5/lib/active_support/tagged_logging.rb:22:in `tagged'
vendor/bundle/ruby/2.5.0/gems/railties-3.2.22.5/lib/rails/rack/logger.rb:16:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_dispatch/middleware/request_id.rb:22:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/rack-1.4.7/lib/rack/methodoverride.rb:21:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/rack-1.4.7/lib/rack/runtime.rb:17:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/activesupport-3.2.22.5/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/rack-1.4.7/lib/rack/lock.rb:15:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/rack-1.4.7/lib/rack/deflater.rb:13:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/actionpack-3.2.22.5/lib/action_dispatch/middleware/static.rb:83:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/rack-ssl-1.3.4/lib/rack/ssl.rb:27:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/rack-cache-1.7.2/lib/rack/cache/context.rb:140:in `forward'
vendor/bundle/ruby/2.5.0/gems/rack-cache-1.7.2/lib/rack/cache/context.rb:249:in `fetch'
vendor/bundle/ruby/2.5.0/gems/rack-cache-1.7.2/lib/rack/cache/context.rb:189:in `lookup'
vendor/bundle/ruby/2.5.0/gems/rack-cache-1.7.2/lib/rack/cache/context.rb:66:in `call!'
vendor/bundle/ruby/2.5.0/gems/rack-cache-1.7.2/lib/rack/cache/context.rb:51:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
lib/rack/assets.rb:167:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
lib/rack/basics.rb:24:in `call'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/railties-3.2.22.5/lib/rails/engine.rb:484:in `call'
vendor/bundle/ruby/2.5.0/gems/railties-3.2.22.5/lib/rails/application.rb:231:in `call'
vendor/bundle/ruby/2.5.0/gems/railties-3.2.22.5/lib/rails/railtie/configurable.rb:30:in `method_missing'
vendor/bundle/ruby/2.5.0/gems/newrelic_rpm-5.1.0.344/lib/new_relic/agent/instrumentation/middleware_tracing.rb:92:in `call'
vendor/bundle/ruby/2.5.0/gems/unicorn-5.4.0/lib/unicorn/http_server.rb:606:in `process_client'
config/unicorn.rb:94:in `process_client_with_gc'
vendor/bundle/ruby/2.5.0/gems/unicorn-5.4.0/lib/unicorn/http_server.rb:701:in `worker_loop'
vendor/bundle/ruby/2.5.0/gems/unicorn-5.4.0/lib/unicorn/http_server.rb:549:in `spawn_missing_workers'
vendor/bundle/ruby/2.5.0/gems/unicorn-5.4.0/lib/unicorn/http_server.rb:142:in `start'
vendor/bundle/ruby/2.5.0/gems/unicorn-5.4.0/bin/unicorn:126:in `<top (required)>'
vendor/bundle/ruby/2.5.0/bin/unicorn:23:in `load'
vendor/bundle/ruby/2.5.0/bin/unicorn:23:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/cli/exec.rb:75:in `load'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/cli/exec.rb:75:in `kernel_load'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/cli/exec.rb:28:in `run'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/cli.rb:424:in `exec'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/vendor/thor/lib/thor.rb:387:in `dispatch'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/cli.rb:27:in `dispatch'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/vendor/thor/lib/thor/base.rb:466:in `start'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/cli.rb:18:in `start'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/exe/bundle:30:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/lib/bundler/friendly_errors.rb:122:in `with_friendly_errors'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/gems/bundler-1.16.1/exe/bundle:22:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/bin/bundle:23:in `load'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/bin/bundle:23:in `<main>'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.5.1-tagX4gpqkt9tzqft/bin/ruby_executable_hooks:15:in `<main>'

I'm trying to understand why this error is happening. Based on the backtrace it doesn't seem to be caused by our code, and since it only happens on some pages of the site I don't think that its a gem compatibility issue. Of note is that the ActionView::Template::Error code is calling sum on an array of strings:

79  def source_extract(indentation = 0)
80    return unless num = line_number
81    num = num.to_i
82
83    source_code = @template.source.split("\n")
84
85    start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
86    end_on_line   = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
87
88    indent = ' ' * indentation
89    line_counter = start_on_line
90    return unless source_code = source_code[start_on_line..end_on_line]
91
92    source_code.sum do |line|
93      line_counter += 1
94      "#{indent}#{line_counter}: #{line}\n"
95    end
96  end

but that does seem to be a valid use of the Array#sum method (https://ruby-doc.org/core-2.5.1/Array.html#method-i-sum). Is this something wrong with our codebase or is there an error in the ActionPack gem?

Select model based on amount of related models with certain conditions

I have a Post that has_many :comments. Let's say Comment has the following field: another_model_id. I would like to select Posts, that have from 2 to 5 comments with another_model_id = 10 (for example). I tried several constructions but with no success :(

Example of what I tried:

# Invalid SQL syntax error
Post
  .joins(:comments)
  .select("count(comment.another_model_id = 10) as comments_count)
  .where("comments_count BETWEEN 2 AND 5")

I have literally no idea where to dig. Is it possible to achieve that in a single query? Thanks!