Monday, January 2, 2017

Ho to write a scope to display ratings for an Event - Rails 5 | Fixed issues

Ho to write a scope to display ratings for an Event - Rails 5 | Fixed issues


Ho to write a scope to display ratings for an Event - Rails 5

Posted: 02 Jan 2017 07:53 AM PST

  • I would like to write a scope that lists all the ratings for an event.
  • can one advise me how to write a scope that list the ratings for the event = Event.find(5) which is represented as :rateable_id => 5

Terminal:

2.3.0 :005 >   event = Event.find(5)    Event Load (0.2ms)  SELECT  "events".* FROM "events" WHERE "events"."id" = ? LIMIT ?  [["id", 5], ["LIMIT", 1]]   => #<Event id: 5, title: "Speed Social - Graduate Professionals", description: "Lorem ipsum dolor sit amet, consectetur adipiscing...", created_at: "2016-12-04 14:02:09", updated_at: "2016-12-04 14:02:09", slug: nil>   2.3.0 :006 >   2.3.0 :007 >     2.3.0 :008 >   ap Rate.all    Rate Load (0.3ms)  SELECT "rates".* FROM "rates"  [      [0] #<Rate:0x007f84fd142380> {                     :id => 8,               :rater_id => 1,          :rateable_type => "Event",            :rateable_id => 5,                  :stars => 3.0,              :dimension => "style",             :created_at => Mon, 02 Jan 2017 15:00:51 UTC +00:00,             :updated_at => Mon, 02 Jan 2017 15:00:51 UTC +00:00      },      [1] #<Rate:0x007f84fd142178> {                     :id => 9,               :rater_id => 4,          :rateable_type => "Event",            :rateable_id => 5,                  :stars => 2.0,              :dimension => "style",             :created_at => Mon, 02 Jan 2017 15:12:29 UTC +00:00,             :updated_at => Mon, 02 Jan 2017 15:12:29 UTC +00:00      },      [2] #<Rate:0x007f84fd141f70> {                     :id => 10,               :rater_id => 1,          :rateable_type => "Event",            :rateable_id => 6,                  :stars => 4.0,              :dimension => "style",             :created_at => Mon, 02 Jan 2017 15:40:37 UTC +00:00,             :updated_at => Mon, 02 Jan 2017 15:40:37 UTC +00:00      }  ]   => nil   

schemas

ActiveRecord::Schema.define(version: 20170102134239) do      create_table "events", force: :cascade do |t|      t.string   "title"      t.text     "description"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.string   "slug"      t.index ["slug"], name: "index_events_on_slug", unique: true    end      create_table "events_users", id: false, force: :cascade do |t|      t.integer "event_id", null: false      t.integer "user_id",  null: false    end      create_table "overall_averages", force: :cascade do |t|      t.string   "rateable_type"      t.integer  "rateable_id"      t.float    "overall_avg",   null: false      t.datetime "created_at"      t.datetime "updated_at"    end      create_table "rates", force: :cascade do |t|      t.integer  "rater_id"      t.string   "rateable_type"      t.integer  "rateable_id"      t.float    "stars",         null: false      t.string   "dimension"      t.datetime "created_at"      t.datetime "updated_at"      t.index ["rateable_id", "rateable_type"], name: "index_rates_on_rateable_id_and_rateable_type"      t.index ["rater_id"], name: "index_rates_on_rater_id"    end      create_table "rating_caches", force: :cascade do |t|      t.string   "cacheable_type"      t.integer  "cacheable_id"      t.float    "avg",            null: false      t.integer  "qty",            null: false      t.string   "dimension"      t.datetime "created_at"      t.datetime "updated_at"      t.index ["cacheable_id", "cacheable_type"], name: "index_rating_caches_on_cacheable_id_and_cacheable_type"    end      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.string   "firstname"      t.string   "lastname"      t.string   "slug"      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true      t.index ["slug"], name: "index_users_on_slug", unique: true    end    end  

How can I automatically run Bundler within the project directory when Vagrant is provisioning?

Posted: 02 Jan 2017 07:09 AM PST

I'd like to Bundler to install Rails project dependencies when Vagrant is provisioning a new VM. This is what I currently have, but I get this line printed ==> default: Could not locate Gemfile or .bundle/ directory. The project directory does contain a Gemfile.

Vagrantfile

# -*- mode: ruby -*-  # vi: set ft=ruby :    VAGRANTFILE_API_VERSION = "2"    Vagrant.require_version ">= 1.9.1"    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|      config.vm.box = "bento/ubuntu-16.04"      # Configurate the virtual machine to use 2GB of RAM    config.vm.provider :virtualbox do |vb|      vb.customize ["modifyvm", :id, "--memory", "2048"]      vb.name = "Nuggets_API_Env"    end      # Forward the Rails server default port to the host    config.vm.network :forwarded_port, guest: 3000, host: 3000      # Use Chef Solo to provision our virtual machine    config.vm.provision :chef_solo do |chef|      chef.cookbooks_path = ["cookbooks"]        chef.add_recipe "apt"      chef.add_recipe "build-essential"      chef.add_recipe "nodejs"      chef.add_recipe "openssl"      chef.add_recipe "ruby_build"      chef.add_recipe "ruby_rbenv::user"      chef.add_recipe "vim"      chef.add_recipe "postgresql::config_initdb"      chef.add_recipe "postgresql::server"      chef.add_recipe "postgresql::client"        chef.json = {        postgresql: {          apt_pgdg_postgresql: true,          version: "9.5",          password: {            postgres: "test1234",          }        },        rbenv: {          user_installs: [{            user: 'vagrant',            rubies: ["2.4.0"],            global: "2.4.0",            gems: {              "2.4.0" => [                { name: "bundler" }              ]            }          }]        },      }    end      config.vm.provision "shell" do |s|      s.path = "VM_Local_Setup.sh"      s.upload_path = "/vagrant/VM_Local_Setup.sh"      s.privileged = false    end    end  

Cheffile

site "https://supermarket.getchef.com/api/v1"    cookbook 'apt'  cookbook 'build-essential'  cookbook 'nodejs'  cookbook 'openssl'  cookbook 'postgresql'  cookbook 'ruby_build'  cookbook 'ruby_rbenv'  cookbook 'vim'  

VM_Local_Setup.sh

#!/bin/bash    sudo apt-get update  sudo apt-get upgrade -y  bundler install  rbenv rehash  

Highcharts Tooltip not rendering properly if it has material icons

Posted: 02 Jan 2017 07:39 AM PST

In my rails application I have a graph with icons generated with Highcharts. The icons are Google Material design icons that I get through a material-icons gem. https://github.com/Angelmmiguel/material_icons.

I want to do 2 things with the icons:

  1. Instead of numeric labels I want smileys. This I got working

    yAxis: {          max: 5,          min: 1,          labels: {              formatter: function () {                  if (this.value == 1) {                      return '<i class="material-icons">sentiment_very_dissatisfied</i>'                  }                  if (this.value == 2) {                      return '<i class="materialicons">sentiment_dissatisfied</i>'                  }                  if (this.value == 3) {                      return '<i class="material-icons" height="5px">sentiment_neutral</i>'                  }                  if (this.value == 4) {                      return '<i class="material-icons">sentiment_satisfied</i>'                  }                  if (this.value == 5) {                      return '<i class="material-icons">sentiment_very_satisfied</i>'                  } else {                      return this.value                  }              }          }      },  

    enter image description here

  2. Instead of numeric values in the tooltip I want smileys. This is where it goes wrong.

    tooltip: {          formatter: function () {              var date = Highcharts.dateFormat('%d-%m-%y %H:%M',                  new Date(this.x));              var getIcon = function (y) {                  if (y == 1) {                      return '<i class="material-icons">sentiment_very_dissatisfied</i>'                  }                  if (y == 2) {                      return '<i class="material-icons">sentiment_dissatisfied</i>'                  }                  if (y == 3) {                      return '<i class="material-icons">sentiment_neutral</i>'                  }                  if (y == 4) {                      return '<i class="material-icons">sentiment_satisfied</i>'                  }                  if (y == 5) {                      return '<i class="material-icons">sentiment_very_satisfied</i>'                  } else {                      return y                  }              };              var icon = getIcon(this.y);              console.log(date);              return '<b>' + this.series.name + '</b><br/>' + date + ' : ' + icon;          },  

    I have to parse the date because it is a JavaScript epoch time(milliseconds). Without + icon the date is shown. If I add + icon it doesn't work and the date will not correctly render. What I noticed is that the icon is higher than the line itself. So I think this is a CSS problem, but I don't know how to fix it.
    Without:withoutWith:with

Thanks in advance for replying!

Update Attributes of a Specific Record

Posted: 02 Jan 2017 06:09 AM PST

Let's say I have a bunch of cards listed on my wall show action. When you interact with a card (click it for example), I want to update that card's attributes.

I'm currently doing this by getting the card's attributes with Javascript, adding them to a card form and submitting the form remotely.

I have the card's ID, but how do I tell the form which card I want to update?

What should the form and controller update action look like?

This is what I have so far

Form

<%= form_for(@card, remote: true) do |f| %>      <%= f.text_field :list_id %>      <%= f.text_field :order %>  <% end %>  

Controller

def update      @card = Card.find(params[:id])        if @card.update_attributes(shared_params)          redirect_to edit_card_path(@card, format: :html)      else          render :edit      end  end  

bootstrap star rating and dynamic tabs conflict

Posted: 02 Jan 2017 06:26 AM PST

In my Rails application I am using bootstrap dynamic tabs which was working fine but when I included the js of bootstrap-star-rating from https://github.com/kartik-v/bootstrap-star-rating/blob/master/js/star-rating.js it stopped working.

This is my Rails application.js file

//= require jquery  //= require jquery_ujs  //= require jquery-ui  //= require bootstrap.min  //= require bootstrap-slider  //= require timepicker.min  //= require modernizr.custom  //= require star-rating  //= require page    

And this is the code for showing bootstrap stars in page.js file:

$(document).ready(function () {      $("a[href='#overview']").click(function(){      $(this).parent('li').addClass('active')      $("[data-toggle=tab]").parent('li').removeClass('active')      $(".tab-pane").addClass('active in')    })        $('.star-rating').rating({min: 0,max: 5,step: 1,size: 'xs',showClear: false,showCaption: false});      $('.star-rating').on('rating.change', function() {      rating = $(this).val()      get_id = $(this).attr('id')      $('input#'+get_id+'_rating').val(rating)    });  

And this is the code for bootstrap tabs.

      %ul.nav.nav-tabs          %li.active            %a{"data-toggle" => "tab",:href => "#overview"} Overview          %li            %a{"data-toggle" => "tab", :href => "#offers"} Offers          %li            %a{"data-toggle" => "tab", :href => "#services"} Services          %li            %a{"data-toggle" => "tab", :href => "#reviews"} Reviews        .tab-content          #overview.tab-pane.active.fade.in            %h3.hidden-heading  Overview            %p= @business["description"]         #offers.tab-pane.active.fade.in  

Ruby on rails Failed to precompile

Posted: 02 Jan 2017 06:17 AM PST

I'm learning to make a web-app for a week and I'm successful to run it locally,but can't push it to heroku master. I get the following error:

enter image description here

Link to specific ajax tab in rails

Posted: 02 Jan 2017 07:37 AM PST

I have a question that I have not found a answer for yet.

In my Rails 4 application I use ajax tabs. Here is an example for the code setup.

show.html.erb

<div id="ajaxtabs">    <ul class="nav nav-tabs">      <li><%= link_to 'Members', some_member_path, :remote => true %></li>      <li><%= link_to 'Hosts', some_host_path, :remote => true %></li>    </ul>   </div>  <div class="tab-content">    <div id="tab-display"></div>  </div>  

members.js.erb

$("#tab-display").html("<%= escape_javascript (render partial: 'members') %>");  

_members.html.erb

 "This is the partial displayed when the members tab is clicked"  

Everything work beautifully, but there is one feature that I would like to get to work, and that is the ability to link to a specific tab.

For example if I would like to link to the members tab I could type the url maybe like? sitename.com/groups/#members-tab

unpermitted parameter simple_form

Posted: 02 Jan 2017 06:17 AM PST

I am trying to create a nested form with Simple_fields in ruby 4. However, every time i try to enter data into the form i get a unpermitted parameter error in the serverconsole after trying to submit. I already tried the sollutions found in the simple_form wiki and did some testing, but that doesn't seem to work.

The _form:

<%= simple_form_for(@enquiry) do |f| %>      <%= f.error_notification %>        <div class="form-inputs">        <H1>Algemene informatie</H1>          <%= f.input :reference, placeholder: 'Referentie' %>        <br>          <%= f.label :Locatie %>        <%= f.select :location, [['Chemiepark', 'chemiepark'], ['Farmsum', 'farmsum'], ['Winschoten', 'winschoten']] %>          <br>        <%= f.input :description, placeholder: 'Omschrijving' %>        <br>        <%= f.input :date %>        <br>        <%= f.input :amount, placeholder: 'Aantal' %>        </div>        <hr>      <% if false %>          <div class="form-inputs">            <%= f.simple_fields_for :enquiry_measures do |e| %>                  <H1>Maatregelen</H1>                  <%= e.input :responsible, placeholder: 'Verantwoordelijke' %>                <br>                <%# e.input :needed, as: :check_boxes,                       collection: ["ja", "nee"] %>            <% end %>            <br>          </div>      <% end %>        <div class="form-inputs">        <%= f.simple_fields_for :tools do |t| %>            <% @enquiry.tools.each do |tool| %>                <%= field_set_tag 'Tool' do %>                    <%= f.simple_fields_for "tool_attributes[]", tool do |tf| %>                        <h1>Gereedschappen</h1>                        <br>                        <%= tf.input :handtool, placeholder: 'Handgereedschap' %>                    <% end %>                <% end %>            <% end %>        <% end %>        </div>      <div class="form-actions">        <%= f.button :submit %>      </div>  <% end %>  

The strong attributes plus what i tested:

def enquiry_params        # was gegenereerd door de scaffold params.fetch(:enquiry, {})        params.require(:enquiry).permit(:reference, :location, :description, :date, :amount,                                        :enquiry_measures_attributes => [:done, :responsible, :needed], :tools_attributes => [:handtool] )                                        #:enquiry_measures_attributes => [:done, :responsible, :needed])                                        #enquiry_measure_attributes: [:done, :responsible, :needed] )  

update code from models

class Enquiry < ActiveRecord::Base    #ophalen van andere tabellen voor het formulier. Has_many is 1 op veel relatie    #accepts_nested_attributes Nested attributes allow you to save attributes on associated records through the paren    # de dere regel zorgt ervoor dat de maatregelen worden opgehaald via de tussentabel enquiry_measures.      has_many :enquiry_measures, :class_name => 'EnquiryMeasure' #, inverse_of: :Enquiry    accepts_nested_attributes_for :enquiry_measures, :allow_destroy => true      has_many :measures, -> { uniq }, :class_name => 'Measure', :through => :enquiry_measures, dependent: :destroy    accepts_nested_attributes_for :measures, :allow_destroy => false      has_many :controls, :class_name => 'Control' #, inverse_of: :Enquiry      has_many :applicants, :class_name => 'Applicant' #, inverse_of: :Enquiry      has_many :agrees, :class_name => 'Agree' #, inverse_of: :Enquiry      has_many :signatures, :class_name => 'Signature' #, inverse_of: :Enquiry    accepts_nested_attributes_for :signatures, :allow_destroy => false      has_many :tools, :class_name => 'Tool', :dependent => :destroy  #, inverse_of: :Enquiry    accepts_nested_attributes_for :tools, :allow_destroy => true      #:dependent => :destroy  zorgt ervoor dat de foreign record ook word verwijderd.      #de instances van andere tabellen:      e = Enquiry.new    e.enquiry_measures.build(:enquiry_id => :id)    e.measures.build        # 28-11 MG de pagina's die in het form worden gebruikt.    cattr_accessor :form_steps do      %w(basic when measurements tool)    end      attr_accessor :form_step      validates :reference, presence: true, if: -> { required_for_step?(:basic) }    validates :amount, :date, presence: true, if: -> { required_for_step?(:when) }    #validates :needed, presence: true, if: -> { required_for_step?(:measurements) }      def required_for_step?(step)      return true if form_step.nil?      return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)    end      #voor het mailen met behulp van de mailgem:    # Declare the e-mail headers. It accepts anything the mail method    # in ActionMailer accepts.    def headers      {          :subject => "My Contact Form",          :to => "marco.groenhof@jpbgroep.nl",          :from => %("#{name}" <#{email}>)      }    end    end  

and 1 of the related models: in this case enquiry_measure

class EnquiryMeasure < ActiveRecord::Base      belongs_to :enquiry      validates_presence_of :enquiry      has_many :measure  #serialize zodat de data uit de collection select met multiple: true op kan worden geslagen.      serialize :measure    end  

and tools:

class Tool < ActiveRecord::Base    belongs_to :enquiry, :class_name => 'Enquiry' #, inverse_of: :applicant    validates_presence_of :enquiry  end  

I know class_name is not really needed anymore.

how do I change environments in ruby on rails [duplicate]

Posted: 02 Jan 2017 05:42 AM PST

This question already has an answer here:

At the moment, I am unable to run my server because apparently I seem to be in the wrong environment.

Suppose I am in the test environment, how do I switch to the production environment? Because right now, every time I am trying to run my app they keep telling me the server is running on the production environment.When I check to see if its running it still says that no application is running....

Is there a command I can use to switch environments?

`method_missing': undefined method `devise' for User error

Posted: 02 Jan 2017 04:22 AM PST

I downloaded devise in Gem of my app.When I did bundle exec rails server -b 0.0.0.0 in terminal,I got a error, .rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5.2/lib/active_record/dynamic_matchers.rb:26:in method_missing': undefined methoddevise' for User (call 'User.connection' to establish a connection):Class (NoMethodError)

I read other error message of above error(it said user.rb:4:in <class:User>' and user.rb:1:in' were wrong)but I don't know why these sentences are wrong(because its part is devise :database_authenticatable, :registerable)

What should I do to fix this error?

I wrote , in user.rb

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable  end

in migrate file,

class DeviseCreateUsers < ActiveRecord::Migration    def change      create_table(:users) do |t|        ## Database authenticatable        t.string :email,              null: false, default: ""        t.string :encrypted_password, null: false, default: ""          ## Recoverable        t.string   :reset_password_token        t.datetime :reset_password_sent_at          ## Rememberable        t.datetime :remember_created_at          ## Trackable        t.integer  :sign_in_count, default: 0, null: false        t.datetime :current_sign_in_at        t.datetime :last_sign_in_at        t.string   :current_sign_in_ip        t.string   :last_sign_in_ip          ## Confirmable        # t.string   :confirmation_token        # t.datetime :confirmed_at        # t.datetime :confirmation_sent_at        # t.string   :unconfirmed_email # Only if using reconfirmable          ## Lockable        # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts        # t.string   :unlock_token # Only if unlock strategy is :email or :both        # t.datetime :locked_at            t.timestamps null: false      end        add_index :users, :email,                unique: true      add_index :users, :reset_password_token, unique: true      # add_index :users, :confirmation_token,   unique: true      # add_index :users, :unlock_token,         unique: true    end  end

in application_controller

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.    before_action :authenticate_user!    protect_from_forgery with: :exception  end

in routes.rb,

Rails.application.routes.draw do        devise_for :users    get 'pages/index'      get 'pages/show'      get 'home/index'      root 'pages#index'    get 'pages/show'      get 'home/index'    root 'home#index'      namespace :connection do        get '/',action:'index'      end  end

mongoid uninitialized constant Point

Posted: 02 Jan 2017 05:37 AM PST

I hear about and try to implement those libraries mongoid-geospatial

But they all mention this class Point which is undefined for me. What am I missing ?

I am adding a geo concern to my models with ActiveSupport::Concern

module Mappable    extend ActiveSupport::Concern      included do      include Mongoid::Geospatial        field :coordinates, type: Point, spatial: true      spatial_scope :coordinates  

uninitialized constant Mappable::Point (NameError)

limit the number of stack trace lines when exception is generated in rails

Posted: 02 Jan 2017 06:15 AM PST

Is there a way i can control the number of stack trace lines generated when a exception scenario happen in a rails application.

The reason for this is i need the stack trace but not all the lines and other reason my log file grows to a huge amount after a while.

Any help would be appreciated. Thanks.

ruby map find_each can't add to array

Posted: 02 Jan 2017 04:44 AM PST

I have 2 Models: Document and Keywords. They are habtm in relation to each other and they both accepts_nested_attributes_for each other so I can create a nested form. That works well.

So in params, I have

"document"=>{"book_id"=>"1", "keywords"=>{"keywords"=>"term, administration, witness "}, ...  

In the controller I put the keywords in a separate array like this :

q = params[:document][:keywords].fetch(:keywords).split(",")  

This works well too.

What I now need to do, is get the keywords ids and put them in an array. Each element of that array will populate the join table.

I've tried this :

a = Array.new  q.each do |var|    id =  Keyword.select(:id).find_by keyword: var    a << id    id  end  

But, this only answers [#<Keyword id: 496>, nil, nil], although the server log shows that all 3 SQL requests are executed and they are correct.

I have also tried this :

a = Array.new  q.map do |e|     Keyword.where(motcle: e).select(:id).find_each do |wrd|       a << wrd.id    end  end  

Then again, this only return the FIRST id of the keyword, although the server log shows that all 3 SQL requests are executed.

What I'm trying to get is a = [496, 367, 2398]

So I have 2 questions :

1/ Why are the ids not added to the array, despite the server executing all SQL requests ?

2/ How to write in rails a request would be

SELECT  "motclefs"."id" FROM "motclefs" WHERE "motclefs"."motcle" in ('déchéances','comtesse') ORDER BY "motclefs"."id";  

Thanks !

ActiveJob spec doesn't work with ActionController::Parameters

Posted: 02 Jan 2017 06:30 AM PST

My test:

describe TasksCsvsController do    describe '#index' do      let(:params) { {'clients' => {'id' => ['1', '2', '3']}} }        before do        ActiveJob::Base.queue_adapter = :test      end        it 'enqueues tasks csv job' do        get :create, params: params        expect(ProjectsCsvJob).to have_been_enqueued.with(params['clients'])      end    end  end  

The controller it tests:

class TasksCsvsController < ApplicationController    def create      ProjectsCsvJob.perform_now(csv_params.to_unsafe_hash)      redirect_to tasks_path, notice: I18n.t('flashes.tasks_csv_generating', email: current_user.email)    end      private      def csv_params      params.require(:clients).permit(:from, :to, tasks_grid: {}, id: [])    end  end  

And the ActiveJob:

class ProjectsCsvJob < ApplicationJob    queue_as :default      def perform(clients_params)      # it does nothing    end  end  

The test doesn't pass:

Failure/Error: expect(ProjectsCsvJob).to have_been_enqueued.with(params['clients'])         expected to enqueue exactly 1 jobs, with [{"id"=>["1", "2", "3"]}], but enqueued 0  

This is strange, because when I debug during the test, params['clients'].to_unsafe_hash is what I expect.

However, when I change the controller's line to

ProjectsCsvJob.perform_later({'id' => ['1', '2', '3']})  

the test passes.

Customize index action in ActiveAdmin

Posted: 02 Jan 2017 07:30 AM PST

I have more than 5 million records in the table (Phone). When I click on Phone Table, It takes more then 5 min. to display a records and on heroku it's going to crash.

I want to customize my index action. I just want to display 10,000 records and other records will be display as per the search query.

How can I do this?

I tried following but it gives me error.

raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object

 controller do      def index          @phones = Phone.limit(10000).page(params[:page])      end        def permitted_params        params.permit!       end    end  

Ruby-on-rails web application could not be started because of 'uglifier'

Posted: 02 Jan 2017 04:02 AM PST

There was an error while trying to load the gem 'uglifier'.

Gem Load Error is: wrong argument type Class (expected Module)  Backtrace for gem load error is:    /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8/conversion.rb:23:in `include'  /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8/conversion.rb:23:in `block (2 levels) in <top (required)>'  /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8/conversion.rb:22:in `class_eval'  /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8/conversion.rb:22:in `block in <top (required)>'  /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8/conversion.rb:21:in `each'  /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8/conversion.rb:21:in `<top (required)>'  /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8.rb:22:in `require'  /usr/local/lib/ruby/gems/2.4.0/gems/therubyracer-0.12.2/lib/v8.rb:22:in `<top (required)>'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs/ruby_racer_runtime.rb:108:in `require'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs/ruby_racer_runtime.rb:108:in `available?'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:63:in `each'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:63:in `find'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:63:in `best_available'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:57:in `autodetect'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs.rb:5:in `<module:ExecJS>'  /usr/local/lib/ruby/gems/2.4.0/gems/execjs-2.7.0/lib/execjs.rb:4:in `<top (required)>'  /usr/local/lib/ruby/gems/2.4.0/gems/uglifier-3.0.4/lib/uglifier.rb:5:in `require'  /usr/local/lib/ruby/gems/2.4.0/gems/uglifier-3.0.4/lib/uglifier.rb:5:in `<top (required)>'  /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:91:in `require'  /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:91:in `block (2 levels) in require'  /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:86:in `each'  /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:86:in `block in require'  /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:75:in `each'  /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:75:in `require'  /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler.rb:106:in `require'  /var/www/geia.junyuzhu.com/public_html/testapp/config/application.rb:7:in `<top (required)>'  /var/www/geia.junyuzhu.com/public_html/testapp/config/environment.rb:2:in `require_relative'  /var/www/geia.junyuzhu.com/public_html/testapp/config/environment.rb:2:in `<top (required)>'  config.ru:3:in `require_relative'  config.ru:3:in `block in <main>'  /usr/local/lib/ruby/gems/2.4.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `instance_eval'  /usr/local/lib/ruby/gems/2.4.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `initialize'  config.ru:1:in `new'  config.ru:1:in `<main>'  /usr/share/passenger/helper-scripts/rack-preloader.rb:110:in `eval'  /usr/share/passenger/helper-scripts/rack-preloader.rb:110:in `preload_app'  /usr/share/passenger/helper-scripts/rack-preloader.rb:156:in `<module:App>'  /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'  /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'  Bundler Error Backtrace:   (Bundler::GemRequireError)    /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:94:in `rescue in block (2 levels) in require'    /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:90:in `block (2 levels) in require'    /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:86:in `each'    /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:86:in `block in require'    /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:75:in `each'    /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:75:in `require'    /usr/local/lib/ruby/gems/2.4.0/gems/bundler-1.13.7/lib/bundler.rb:106:in `require'    /var/www/geia.junyuzhu.com/public_html/testapp/config/application.rb:7:in `<top (required)>'    /var/www/geia.junyuzhu.com/public_html/testapp/config/environment.rb:2:in `require_relative'    /var/www/geia.junyuzhu.com/public_html/testapp/config/environment.rb:2:in `<top (required)>'    config.ru:3:in `require_relative'    config.ru:3:in `block in <main>'    /usr/local/lib/ruby/gems/2.4.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `instance_eval'    /usr/local/lib/ruby/gems/2.4.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `initialize'    config.ru:1:in `new'    config.ru:1:in `<main>'    /usr/share/passenger/helper-scripts/rack-preloader.rb:110:in `eval'    /usr/share/passenger/helper-scripts/rack-preloader.rb:110:in `preload_app'    /usr/share/passenger/helper-scripts/rack-preloader.rb:156:in `<module:App>'    /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'    /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'  

I have tried to install nodejs and restart the apache server. It doesn't help with this issue.

bundle show uglifier gives

/usr/local/lib/ruby/gems/2.4.0/gems/uglifier-3.0.4  

I assume I have uglifier installed correctly.

Also gem 'therubyracer', platforms: :ruby is uncommented in Gemfile.

Please help, I have no idea how to solve this issue.

close zelect dropdown on click of a sibling

Posted: 02 Jan 2017 07:20 AM PST

I have following html code ( Rails erb view )-

<%= select_tag :destination, options_for_select(@destinations, params["destination"]), :id => 'destination', :style => 'width:100%;' %>  <div class='dropdown-icon destination-icon'>   <i class='fa fa-chevron-down'></i>  </div>  

& following js code -

  $(document).click(function(){      $('.zelect').removeClass("open");      $('.zelect .dropdown').hide();    })      $('.zelect').click(function(e){      e.stopPropagation();    })      $('.dropdown-icon.destination-icon').click(function(e){      var zelect = $(this).siblings(".zelect");      if( zelect.hasClass("open") ){        zelect.removeClass("open");        zelect.children(".dropdown").hide();      }      else{        zelect.addClass("open");        zelect.children(".dropdown").show();                  }        });    

What I want to do is close zelect dropdown on clicking anywhere except for zelect input & destination-icon.

How do I do it ?

Adding raygun to app X would overwrite existing vars RAYGUN_APIKEY (Ruby on Rails)

Posted: 02 Jan 2017 03:21 AM PST

I am trying to add Raygun to a new RoR Heroku app X, but it says "Item could not be created: Adding raygun to app X would overwrite existing vars RAYGUN_APIKEY".

I deleted the old RAYGUN_APIKEY api key and it does not show in the heroku list of keys (figaro heroku:set -e production), but it seems that heroku still finds this key.

How could I fix this issue?

Ajax not working inside iteration

Posted: 02 Jan 2017 04:15 AM PST

I have a AtpRank model containing the first 100 Atp tennis players.
My goal is to create in the view a table listing all tennis players and their attributes, along with a button for each player useful for the user to choose a list of tennis players. The home.html.erb code is below:

<% @atp_ranks.each do |tennis_player| %>    <tr id="tennist-<%= tennis_player.ranking %>">      <td class="atpranking"> <%= tennis_player.ranking %> </td>      <td class="atpname"> <%= tennis_player.name %> </td>      <td class="atppoints"> <%= tennis_player.points %> </td>      <% unless Time.now.month == 12 %>        <td>          <div id="atpenlist_form">            <% if current_user.atpenlisted?(tennis_player) %>              <%= form_for(current_user.atp_selections.find_by(atp_rank_id: tennis_player.id),                                                   html: { method: :delete }, remote: true) do |f| %>                <%= f.submit "Dump", class: "btn btn-warning btn-sm" %>              <% end %>            <% else %>              <%= form_for(current_user.atp_selections.build, remote: true) do |f| %>                <div><%= hidden_field_tag :atp_id, tennis_player.id %></div>                <%= f.submit "Choose", class: "btn btn-primary btn-sm" %>              <% end %>            <% end %>          </div>        </td>      <% end %>    </tr>  <% end %>  

As you can see, the form uses Ajax having set remote: true in the form_for helper. Requests are handled by the atp_selections controller. Below is an extract of the create action of this controller:

    current_user.atpenlist(tennist)      respond_to do |format|        format.html { redirect_to root_url }        format.js      end  

The destroy action uses the atpdiscard method instead of the atpenlist method.
In app/views/atp_selections I created the create.js.erb and destroy.js.erb files.
Below is the app/views/atp_selections/create.js.erb file:

$("#atpenlist_form").html("<%= escape_javascript(render('users/atpdiscard')) %>");  $("#atp_count").html('<%= current_user.atp_ranks.count %>');  

Each of the app/view/users/_atpenlist.html.erb and app/view/users/_atpdiscard.html.erb partials contain the respective form (the same exact part of the code above starting with form_for).

I have to say that in the original code for the home page I did not explicitly included the entire code for the forms, but I just rendered the partials. This did not work: rails warned me that it could not find the variable or method tennis_player used in the iteration, for some reason to me unknown. So I had to renounce to render the partials and decided to include the entire code.

The issue is now that Ajax does not work: I have to refresh the page to see the results of submitting the form. I checked my code and could not find errors or explanation for this.

How to fix the pluralization for comments and likes in rails

Posted: 02 Jan 2017 06:34 AM PST

I am new to rails, and i am working on a rtl website in Arabic! I am trying to fix the pluralization in comment.count and get_upvotes.size to be replaced by the arabic words. I have heard the I can do it with Rails Internationalization (I18n) but I could not find a clear answer to my question.

I would appreciate the help. Let me know if more information is needed! Thanks

ERROR: Error installing mysql2: ERROR: Failed to build gem native extension. on Mac 10.12

Posted: 02 Jan 2017 03:17 AM PST

I tried every solution similar to the question:

Recently , I moved from ubuntu to Mac and I'm trying to install mysql gem on Sierra and after I had installed Ruby , Rails , Mysql,

also I type brew install mysql and it worked for download mysql but not the gem , so my question is not similar.

I typed this mysql --version

and I got mysql Ver 14.14 Distrib 5.7.16, for osx10.12 (x86_64) using EditLine wrapper

I tried to install mysql2 gem for rails to build a new app

I typed this sudo gem install mysql2 and got this error:

Password:  Building native extensions.  This could take a while...  ERROR:  Error installing mysql2:  ERROR: Failed to build gem native extension.    current directory: /Users/mohammed.elias/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/ext/mysql2  /Users/mohammed.elias/.rbenv/versions/2.4.0/bin/ruby -r ./siteconf20170102-2045-18gcs95.rb extconf.rb  checking for rb_absint_size()... yes  checking for rb_absint_singlebit_p()... yes  checking for ruby/thread.h... yes  checking for rb_thread_call_without_gvl() in ruby/thread.h... yes  checking for rb_thread_blocking_region()... no  checking for rb_wait_for_single_fd()... yes  checking for rb_hash_dup()... yes  checking for rb_intern3()... yes  checking for rb_big_cmp()... yes  -----  Using mysql_config at /usr/local/bin/mysql_config  -----  checking for mysql.h... yes  checking for SSL_MODE_DISABLED in mysql.h... yes  checking for SSL_MODE_PREFERRED in mysql.h... yes  checking for SSL_MODE_REQUIRED in mysql.h... yes  checking for SSL_MODE_VERIFY_CA in mysql.h... yes  checking for SSL_MODE_VERIFY_IDENTITY in mysql.h... yes  checking for errmsg.h... yes  checking for mysqld_error.h... yes  -----  Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load  -----  -----  Setting libpath to /usr/local/Cellar/mysql/5.7.16/lib  -----  creating Makefile    To see why this extension failed to compile, please check the mkmf.log which can be found here:      /Users/mohammed.elias/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-16/2.4.0-static/mysql2-0.4.5/mkmf.log    current directory:     /Users/mohammed.elias/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/ext/mysql2  make "DESTDIR=" clean    current directory:     /Users/mohammed.elias/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/ext/mysql2  make "DESTDIR="  compiling client.c  compiling infile.c  compiling mysql2_ext.c  compiling result.c  compiling statement.c  linking shared-object mysql2/mysql2.bundle  ld: library not found for -lssl  clang: error: linker command failed with exit code 1 (use -v to see invocation)  make: *** [mysql2.bundle] Error 1    make failed, exit code 2    Gem files will remain installed in     /Users/mohammed.elias/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysq l2-0.4.5 for inspection.  Results logged to     /Users/mohammed.elias/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-16/2.4.0-static/mysql2-0.4.5/gem_make.out  

Undefined variable: "$global-breakpoint" wherever stylesheet_link_tag and javascript_link_tag is mentioned

Posted: 02 Jan 2017 02:39 AM PST

I have recently upgraded my Rails 3.2 application to Rails 5. After managing to run the application when I tried to access some pages this is the error I encountered:

Undefined variable: "$global-breakpoint".    Extracted source (around line #2)    <div ng-controller="navigationController">  <%= stylesheet_link_tag 'header_b2c', media: 'all', 'data-turbolinks-track' => true %>  <% current_user = nil unless defined?(current_user) %>  

This is happening at all the places wherever I am using the stylesheet_link_tag or javascript_link_tag. The header_b2c in the case above is a normal css file in the assets/stylesheets directory.

The same code used to work in rails 3.2. Searching for the error yields almost no result, is it something related to a config thing that I need to do in order to make the css files get interpreted as a css file instead of a sass file ? If not, what else might be the issue ?

NoMethodError in ConnectionController#index

Posted: 02 Jan 2017 02:38 AM PST

When I access localhost:3000, my browser told error of NoMethodError in ConnectionController#index. Also,I was told that undefined method `action' for ConnectionController(Table doesn't exist):Class.

The error browser told connection_controller.rb of 26 line was wrong but I didn't write codes so long like 26 lines.

 send(name, *arguments, &block)        else          super        end      end

I wrote ,in connection_controller.rb

class ConnectionController <  ActiveRecord::Base      def index          personal = {'name'=>'Yamada','old'=>28}          render :json => personal        end  end

in routes.rb,

Rails.application.routes.draw do        namespace :connection do        get '/',action:'index'      end  end

in schema.rb

ActiveRecord::Schema.define(version: 20170101073143) do      create_table "userdata", force: :cascade do |t|      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end    end

in migrate file ,

class CreateUserdata < ActiveRecord::Migration    def change      create_table :userdata do |t|       t.string :name        t.text :image        t.timestamps null: false      end    end  end

in model,

class Userdatum < ActiveRecord::Base  	user = User.new  	user.name = "XXX"  	user.email = "mail"  	user.save  end

Postgres permission denied for relation schema_migrations

Posted: 02 Jan 2017 02:02 AM PST

Busy getting a PG DB working using a db user called shine. Following the book Rails, Angular, Postgres and Bootstrap: I initiated with:

createuser --createdb --login -P shine

bundle exec rails db:create

works.

bundle exec rails db:migrate

gives:

bundle exec rails db:migrate  rails aborted!  ActiveRecord::StatementInvalid: PG::InsufficientPrivilege: ERROR:  permission denied for relation schema_migrations  : SELECT "schema_migrations".* FROM "schema_migrations"  bin/rails:4:in `require'  bin/rails:4:in `<main>'  PG::InsufficientPrivilege: ERROR:  permission denied for relation schema_migrations  bin/rails:4:in `require'  bin/rails:4:in `<main>'  Tasks: TOP => db:migrate  (See full trace by running task with --trace)  

in psql \list gives:

shine_development              | shine       | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =Tc/shine                  +                                  |             |          |             |             | shine=CTc/shine   shine_test                     | shine       | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =Tc/shine                  +                                  |             |          |             |             | shine=CTc/shine  

I have tried all the ALTER, GRANT and OWNER TO commands I could pretty much find out there. What's going on?

database.yml

default: &default    adapter: postgresql    encoding: unicode    host: localhost    username: shine    password: shine    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>    development:    <<: *default    database: shine_development

Missing files in Ubuntu bash on Windows 10

Posted: 02 Jan 2017 02:00 AM PST

Im running Ubuntu bash on Windows 10 and I have an issue with files not showing in Bash while they exist in my Windows 10 environment.

For example when i run the ls command i get the following:

application.html.haml mailer.html.haml mailer.text.haml

I'm missing a folder there (shared). When i go to this very same folder in Windows i see the following: enter image description here

How is it possible Bash is not showing these files? When i run my rails app i get an error for a missing partial file, which is located in the sharedfolder.

This is my gemfile:

gem 'rails', '~> 5.0.1'  gem 'sqlite3'  gem 'puma', '~> 3.0'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.2'    gem 'jquery-rails'  gem 'turbolinks', '~> 5'  gem 'jbuilder', '~> 2.5'    gem 'haml'  gem 'bootstrap-sass', '~> 3.3.6'  gem 'devise'  gem 'awesome_print', :require => 'ap'  gem "select2-rails"  gem 'font-awesome-rails'  gem 'omni_kassa'  gem 'seed_dump'  gem 'jquery-datetimepicker-rails'  gem "cancan"  gem 'binding_of_caller'    group :development, :test do    gem 'byebug', platform: :mri  end    group :development do    gem 'web-console', '>= 3.3.0'    gem 'listen', '~> 3.0.5'      gem 'spring'    gem 'spring-watcher-listen', '~> 2.0.0'      gem 'erb2haml'    gem 'annotate', "~> 2.6.5"    gem 'better_errors'  end  

Rails: Byebug doesn't print in console

Posted: 02 Jan 2017 03:17 AM PST

From some unknown reasons, Byebug stops printing code in console.

For example, I've added byebug in following test:

enter image description here

What I've got in console / terminal:

enter image description here

Do you have any idea what could be wrong or where could I search for a reason of this problem?

EDIT:

Command how I run tests:

$ rake spec  

EDIT 2:

When I run server with Byebug in any place it also doesn't work. It even doesn't print any logs. This is how does it look console after running server and sending to them some requests - ... empty:

enter image description here

That does it doesn't print in console could be caused by puma.rb configuration:

min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { 5 }.to_i  max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 }.to_i  threads min_threads_count, max_threads_count    bind "unix:///var/run/puma.sock?umask=0000"    stdout_redirect "/var/log/puma.stdout.log", "/var/log/puma.stderr.log", true    environment ENV.fetch('RAILS_ENV') { 'development' }    plugin :tmp_restart  

ActiveRecord callback or MySql trigger?

Posted: 02 Jan 2017 05:47 AM PST

Lets say we have two models:

class Message < ActiveRecord::Base    belongs_to :user    has_many :statistics  end    class Statistic < ActiveRecord::Base    belongs_to :user    belongs_to :messages  end  

The Message has :state attribute and it has to be updated based on Statistic counts (i.g. delivered_at, read_at). Meaning once the message was delivered to every user in the group the state has to be updated accordingly.
The Statistics timestamps updated in a sidekiq jobs with a query that does not invoke the callback (update_all) so I can't hook into 'after_update' callback of the Statistics and update the Message.state.
I've tried to do it using MySql after update trigger on Statistics table but had no luck because the query that invokes the trigger has the destination table (messages) in join.
Please advise.
Hope I was clear enough.
Thank you.

Rails: Enable users to choose their roles when signing up on devise

Posted: 02 Jan 2017 01:49 AM PST

I'm using devise for my Rails project to authenticate users. There are several roles that users can choose from (e.g. admin, student, teacher), and I want the users to be able to choose their role when signing up.

I've searched around and found ways to set a default role and enable users to change that role later, but I couldn't find a good resource for how to modify the devise controller and view to allow users to choose their role right away.

Can someone point me to a tutorial or something that they know would be helpful?

Terminal does not work after running rails server

Posted: 02 Jan 2017 01:40 AM PST

after running "rails server" on my mac to start my application, my terminal does not allow me to write commands in the terminal. All I get is the following, with the problem that I can not write any commands.

Last login: Mon Jan  2 13:19:07 on ttys001  Nicholass-MacBook-Pro:~ nicholaswenzel$ cd last_test  Nicholass-MacBook-Pro:last_test nicholaswenzel$ cd nofuckingidea  Nicholass-MacBook-Pro:nofuckingidea nicholaswenzel$ rails s  => Booting WEBrick  => Rails 4.2.6 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  [2017-01-02 13:23:18] INFO  WEBrick 1.3.1  [2017-01-02 13:23:18] INFO  ruby 2.2.3 (2015-08-18) [x86_64-darwin15]  [2017-01-02 13:23:18] INFO  WEBrick::HTTPServer#start: pid=8743 port=3000  

Can anyone help?

Work around CORS Ember error for a Rails backend

Posted: 02 Jan 2017 12:14 AM PST

Building a front end interface using a Rails REST API, I get the error

XMLHttpRequest cannot load http://www.example.com/questions  No 'Access-Control-Allow-Origin' header is present on the requested   resource. Origin 'http://localhost:4200' is therefore not allowed access.  

I've set up my adapter to be

import DS from 'ember-data';    export default DS.RESTAdapter.extend({    namespace: 'api/v1',    host: 'http://www.example.com'  });  

If I was building the API, I would just include the gem 'rack-cors' and allow for the access to other sites, but this is not included in the source. I'm just starting out with the Ember framework and haven't yet found a work around for this.

I've tried running a proxy server

ember s --proxy http://www.example.com  

But I get the same response. Is there a piece of middleware or a method on the RESTAdapter that I can use to bypass this error?

Sunday, January 1, 2017

Capistrano 3.0 Rails 5.0.0 database custom task | Fixed issues

Capistrano 3.0 Rails 5.0.0 database custom task | Fixed issues


Capistrano 3.0 Rails 5.0.0 database custom task

Posted: 01 Jan 2017 07:05 AM PST

I have deployed a Rails app on an Ubuntu server with Capistrano. However I am trying to run a custom task I had created and is in 'lib/tasks'. I tried to make it work by executing

cap production db:views

As if it was a custom task, but obviously it did not worked

cap aborted! Don't know how to build task 'db:views'

The file is sql_views.rake, this task is for create views in the database

namespace :db do    desc "Update and create SQL views"    task :views => :environment do      Dir["#{Rails.root}/db/sql_views/*.sql"].each do |file_name|        STDERR.puts "Applying the SQL view at #{file_name}"        source_file = File.new(file_name, 'r')          if source_file and (sql_content = source_file.read)          ActiveRecord::Base.transaction do            # Each statement ends with a semicolon followed by a newline.            sql_lines = sql_content.split(/;[ \t]*$/)            if sql_lines.respond_to?(:each)              sql_lines.each do |line|                ActiveRecord::Base.connection.execute "#{line};"              end            end          end # transaction        end        end # Dir.each    end # task  end  

Rails and SQL straight request

Posted: 01 Jan 2017 07:01 AM PST

In rails we have Model.find(id_number) request. What I want to ask is there any possibility to create straight request to DB, for example: SELECT * FROM users WHERE id = 1 and replace rails basic Model.where(id: 1)?

Admin user: Rails Environment variable

Posted: 01 Jan 2017 07:29 AM PST

How can one use the rails environment variables within the application?

I am trying to use them to limit access to certain elements on the page. E.g. the users do not see the information an admin does; but the rest of the page is the same. Is there a best practice for such user privilege implementations?

Ruby extra all attribute from img tag

Posted: 01 Jan 2017 06:09 AM PST

I was trying to use nokogiri to turn this line

<img class="img-responsive" src="img/logologo.png" alt="">   

to

<%= image_tag('img/logologo.png', :class => 'img-responsive', :alt => '') %>  

Here is my code

# a = <img class="img-responsive" src="img/logologo.png" alt="" width="256" height="256">   page = Nokogiri::HTML(a)  img = page.css('img')[0]  src =  ""  alt =  ""  class_atr = ""  src =  img['src'] if img['src'].present?  alt =  img['alt'] if img['alt'].present?  class_atr = img['class'] if img['class'].present?  result = "<%= image_tag(\'" + src + '\', :class => \'' + class_atr + '\', :alt => \'' + alt + '\')%>'  

This is kind of like hard code, is there a way I can extra all attribute name and its volume?

Maybe the image tag may contain height or width, how do I extra all attribute automatically and make it into erb style?

Icon within a link_to tag with <a> tags

Posted: 01 Jan 2017 07:40 AM PST

I have a navbar button:

<%= link_to new_post_path do %>    <a class="btn-navbar"><i class="fa fa-plus" aria-hidden="true"></i></a>  <% end %>  

It does not allow me to click it and navigate to the correct page.

If I remove the <a> tags, it works but I need the <a> because its have the correct class associated with it to style the button.

The above code is styled correctly but when trying to click it it does not link to the right page.

Asynchronously log every request for current_user

Posted: 01 Jan 2017 04:16 AM PST

I'm tracking last web session when a user is logged in.

I plan to put this in a background job, and trigger it in ApplicationController since it will be for almost every request.

I currently set current_user in a before_action:

def current_user    if session[:user_id]      @current_user ||= User.find(session[:user_id])    end  end  

The trigger in an after_action:

def log_session    WebSessionJob.perform_later(current_user) if current_user.present?  end  

I'm thinking correctly structuring the code like this?

Making column in Database cannot be done

Posted: 01 Jan 2017 03:59 AM PST

Making column in Database cannot be done in my app. I did 'rails g model userdata' and 'rake db:migrate' ,so I could create create_table(:userdata) and could get below file.

class CreateUserdata < ActiveRecord::Migration    def change      create_table :userdata do |t|       t.string :name        t.text :image        t.timestamps null: false      end    end  end  

Furthermore,I did 'rake db:migrate',in Sequel Pro userdata table could be made but name&image column could not be made.What should I do to make name&image column?

In schema.rb,I wrote

ActiveRecord::Schema.define(version: 20170101073143) do      create_table "userdata", force: :cascade do |t|      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end    end  

Documents on a rails website

Posted: 01 Jan 2017 03:19 AM PST

I am developing a portal of sorts in Ruby on Rails using PostgreSQL. I require different pages (each page represents a different topic of interest) on the portal to show different documents. The admin will have the ability to upload additional documents to each page. No where is the entire list of documents on the website required

What is the best practice to implement such a system and is there any tutorials for the same?

Spree Associate user with order with Login

Posted: 01 Jan 2017 02:44 AM PST

I have a Spree application with the ability to login with Facebook and other social networks , but my problem is that i can't associate user with orders in login , i've tried associate_user! like my following sample but the cart is always empty .

here's my code in omniauthcallback

if current_order      current_user = spree_current_user || @user      current_order.associate_user!(current_user)      session[:guest_token] = nil  end  

Deployment issue with Elasticsearch and Sidekiq using Redis on Heroku Rails 5

Posted: 01 Jan 2017 02:52 AM PST

Problem: my search queries using Elasticsearch with Sidekiq to process background jobs are not working. Search feature is working in localhost but not in production on Heroku. WHY? Damn it.

Thoughts:

  1. Should I upgrade to Professional Dyno? On Heroku Dashboard, I have exceeded Memory Usage for Hobby dyno or are there any other ways to lower it? (Max: 734 MB, Average: 397 MB)

  2. Was my sidekiq.rb configured correctly?

  3. Is it normal to have such high memory usage for Sidekiq background processing? (hmm, everything looks normal and decent except for memory usage)

Attempts:

I googled a lot, and I have seen how other people implemented initializer/sidekiq.rb and followed. No success. Followed doc from Sidekiq Wiki(https ://github.com/mperham/sidekiq/wiki/Using-Redis) (sorry... I can only put two links rn since I'm new) and Julianee's Guide (http: //julianee.com/rails-sidekiq-and-heroku/) but did not work. There were more bugs along the way but I fixed them all. However, I am NOT sure about this one... I've been stuck. Hopefully, if you have better understanding in backend, please teach me THE WAY...:)

The error I got before(I followed Julianee's Guide and got it. Later, I changed it back to Sidekiq Wiki. )...

2017-01-01T09:23:11.150280+00:00 heroku[web.1]: Process running     mem=530M(103.5%)  2017-01-01T09:23:11.150280+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)  2017-01-01T09:23:16.091264+00:00 app[worker.1]: D, [2017-01-    01T09:23:16.091146 #4] DEBUG -- :     Delayed::Backend::ActiveRecord::Job     Load (2.8ms)  UPDATE "delayed_jobs" SET locked_at = '2017-01-01     09:23:16.087535', locked_by = 'host:aa0b7e74-6cb0-4548-b002-dec01f0bb60a pid:4' WHERE id IN (SELECT    "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2017-01-01 09:23:16.086816' AND (locked_at IS NULL OR locked_at < '2017-01-01   05:23:16.086898') OR locked_by = 'host:aa0b7e74-6cb0-4548-b002-  dec01f0bb60a pid:4') AND failed_at IS NULL) ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING *  

The error I have right now (used Sidekiq Wiki)

error 1/2 error 2/2

Also, I get the Application error when I try to load the page at the first time. After that, I don't get any errors but search feature is not working. Ironically, everything works well on localhost:3000.

initializers/sidekiq.rb

if Rails.env.production?      Sidekiq.configure_server do |config|      config.redis = { url: [ENV['REDIS_URL'] } #env variables saved in Heroku.    end      Sidekiq.configure_client do |config|      config.redis = { url: ENV['REDIS_URL'] }    end  end  

procfile

web: bundle exec puma -C config/puma.rb

worker: rake jobs:work

gemfile

gem "sidekiq"

gem 'delayed_job_active_record' <-- added it thinking if the issue was the concurrency... Well, it kinda was but still the search didn't work

gem 'redis'

gem 'rails', '5.0.0'

gem 'bcrypt', '3.1.11'

gem 'faker', '1.6.3'

gem 'carrierwave', '0.11.2'

gem 'mini_magick', '4.5.1'

gem 'elasticsearch-rails'

gem 'elasticsearch-model'

gem 'wepay'

gem 'fog', '1.38.0'

gem 'will_paginate', '3.1.0'

gem 'bootstrap-will_paginate', '0.0.10'

gem 'bootstrap-sass', '3.3.6' gem "font-awesome-rails" gem 'puma', '3.4.0' gem 'sass-rails', '5.0.6' gem 'uglifier', '3.0.0' gem 'coffee-rails', '4.2.1' gem 'jquery-rails', '4.1.1' gem 'turbolinks', '5.0.0' gem 'jbuilder', '2.4.1' gem "mailboxer" gem 'gravatar_image_tag' gem 'jquery-turbolinks' gem 'geocoder' gem 'impressionist' group :production do gem 'pg', '0.18.4' end gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

If none of these are causing issues, I need to check my Indexer.rb (which is basically helper for indexing models with the Sidekiq background workers for Elasticsearch) and (maybe?) my module searchable.rb (which is settings that I had to setup for Elasticsearch queries). I will add more pictures of some parts of my code if you need more information... As I said, I can only add two links/photos in this post for now... Thank you all, hope you learn something or decide to help me out, and Happy New Year :) I won't stop debugging.

Find and update a collection in JSONB

Posted: 01 Jan 2017 02:51 AM PST

I have a Rails 5.0 app with a JSONB column called data, which contains an array of hashes:

[      {'event': 'web_session', 'user_id': 1, 'count': 13},      {'event': 'web_session', 'user_id': 2, 'count': 10},      {'event': 'web_session', 'user_id': 3, 'count': 42}  ]  

How would I update one of the hashes, e.g. matching 'user_id': 2, with a different count value?

Is this the most efficient way (I'd potentially have ~1 million hashes):

h = data.find {|h| h['user_id'] == 2}  h['count'] = 43  save  

rails - left shift "<<" operator saves record automatically

Posted: 01 Jan 2017 05:08 AM PST

Need help understanding this code, as what to my knowledge I know "<<" append to a collection but here it saves the record correctly, how come it does without calling .save method?

#user.rb   has_many :saved_properties, through: :property_saves, source: :property    #users_controller.rb  def update    if @user.saved_properties << Property.find(params[:saved_property_id])          render plain: "Property saved"  end  

Rails Active Admin form display based on checked booleans?

Posted: 01 Jan 2017 12:29 AM PST

I've got a simple Active Admin form that is displaying a lot of form fields, but only some of the form fields will be needed if a boolean is checked on that record. Is there a way to make those forms fields show up only if a boolean is clicked? Is it possible to show forms based on if a cell has any information in it? For example, from my Active Admin page:

form do |f|    f.inputs do      f.input :name      f.input :active      f.input :use_image  <---------------  this is a boolean      if :use_image_boolean_is_clicked         f.input :image_link  ## show form only after :use_image is clicked?      end      f.input :product_1  <---------------  this is a text field      if :product_1_form_has_any_text_in_it          f.input :proudct_1_link  ## show form only after :product_1 has text in it?      end      f.input :product_2  <---------------  this is a text field      if :product_2_form_has_any_text_in_it         f.input :product_2_link  ## show form only after :product_2 has text in it?      end      f.input :text      f.input :alt_text   end  end  

Thanks in advance for any and all help!

AngularJS ng-change does not work when get request with Ruby on Rails 5

Posted: 01 Jan 2017 06:31 AM PST

I'm using ...

  • Ruby on Rails 5
  • AngularJS 1.3.20
  • Chrome or FireFox Browser

It seems ng-change event does not work, when I request get method like link from other page. But when I user POST request to next page, it works.

When I change select box value, onchange event is not happen. I expect ng-change should reach changeHandler function in sample.js and console.log("ChangeHandler!!!") show up.

In addition, I use Ruby on Rails application template. So ng-app and ng-controller is same as index1.html and index2.html.

** Additional Info I tried Chrome ng-inspector for AngularJS Tool. But There is no angular panel shown up. But once reload same page, it shows up. What happend?

index1.html.erb

<html lang="ja" ng-app="MyApp">  <body ng-controller="MyController">    <!-- For GET Method Request -->    <div>      <%= link_to 'Index2', sample_index2_path %>    </div>      <!-- For POST Method Request -->    <div>      <%= form_tag sample_index2_path do %>        <%= button_tag "Click" %>      <% end %>    </div>  </body>  </html>  

index2.html.erb

<html lang="ja" ng-app="MyApp">  <body ng-controller="MyController">    <div>      <form>        <select id="eventTest" ng-model="eventTest" ng-change="changeHandler()">          <option value="1">AAA</option>          <option value="2">BBB</option>          <option value="3">CCC</option>        </select>      </form>    </div>  </body>  </html>  

sample.js

angular.module('MyApp',[])      .controller("MyController", ['$scope', function($scope) {      $scope.eventTest;        $scope.changeHandler = function () {          console.log("ChangeHandler!!!");      };  }]);  

This works only POST, or Get and reload Browser. There are any difference between output HTML source code GET and POST. I'm stack over 3 days.

Please let me know and advice for me.

How to debug Mailboxer gem?

Posted: 31 Dec 2016 11:46 PM PST

I believe I setup mailboxer gem correctly. Messages work. In my User.rb model I have:

  def mailboxer_email(object)      email    end  

However no email gets sent to the receiving user when said user receives a message (I believe by default mailboxer should send this email).

How should I begin debugging this?

Currently, in my messages_controller.rb I have tried manually sending the email:

Mailboxer::MessageMailer.new_message_email("You have received a new message.", recipients)  

But I'm not sure if it's working...

Rake task to fetch current price and update object attribute

Posted: 31 Dec 2016 11:15 PM PST

I have a Portfolio model and am currently running rake tasks to fetch updated price data from Yahoo Finance API, updating the amounts for the Portfolios and create a new Valuation object that takes a snapshot of each portfolio and their values.

A Portfolio has_many Positions that store tickers and their prices. Positions has a has_many association to Movements that act as buy/sell actions and add/subtract from a Portfolio's amount.

The Portfolio methods I'm using to fetch updated price data and update my portfolio amount are:

def new_price_data    price_array = []    if !positions.empty?      positions.each do |pos|        price = YAHOO_CLIENT.quotes([pos.ticker], [:last_trade_price]).first        price = price['last_trade_price'].to_f        price = price * pos.quantity        price_array << price      end    else      price_array << 0    end    price_array  end    def calculate_amount    price = self.new_price_data.inject(&:+)    price  end    def update_portfolio_amount    update_attribute(:amount, self.calculate_amount.round(2))  end  

In my rake file I have an update_price task in the valuation namespace:

desc "Retrieve real-time price data"   task update_price: :environment do    Portfolio.all.each do |portfolio|      portfolio.update_portfolio_amount    end  end  

When I run the body of the task (Portfolio.all.each...) it runs on all my Portfolio objects. For some reason it doesn't run when I schedule it in my cron tab with whenever.

every 1.day, :at => '1:55 am' do    rake "valuation:update_price", :environment => 'development'  end  

My other rake task that is simply creating a new Valuation object on all Portfolios and taking a snapshot of their values for a given day works fine.

I've tested this using rake valuation:update_price. There is a message saying

Running via Spring preloader in process 23522  

but when I check my Portfolios my rails console, they haven't updated. I'm not sure where my error is?

On rails configuration, use systematically the latest installed version of Ruby

Posted: 01 Jan 2017 05:08 AM PST

Since when I execute "bundle install" I get the message error:

Gem::InstallError: devise requires Ruby version >= 2.1.0.  An error occurred while installing devise (4.2.0), and Bundler cannot continue.  

Which is the simplest way, to put as a default version, the last one (ruby 2.3.3 that I already installed), as it seems that I still use the old version, as indicated on Rails configuration Rails_configuration

Through my different searches on google, I couldn't manage to find a simple solution; As I will not use anymore the old versions, a solution like RVM seems too complicated, my wish is just to use the latest installed version of Ruby, as the default version on Rails PS: I am on windows Many thanks

Missing Cookbooks with chef kitchen

Posted: 01 Jan 2017 12:47 AM PST

Trying to setup a rails app using chef but getting Missing Cookbooks error.

Steps to Reproduce

$ chef generate app chef_rails #create new app that will hold cookbooks for rails.  $ echo "cookbook 'ruby-ng'" >> cookbooks/chef_rails/Berksfile  $ cd cookbooks/chef_rails/  $ berks install  $ berks vendor  $ cd ../../  $ vim .kitchen.yml #add `recipe[ruby-ng::default]` to runlist  $ kitchen converge  

Which gives the following error:

Missing Cookbooks: ------------------ No such cookbook: ruby-ng

   Expanded Run List:     ------------------     * chef_rails::default     * ruby-ng::default  

For this, I search the existing answers on stackoverflow & figured that if I move vendored cookbooks, chef is able to find them

$ mv cookbooks/chef_rails/berks-cookbooks/* cookbooks  $ ls cookbooks                                                                                          apt             chef_rails      mingw           ruby-ng         windows  build-essential compat_resource ohai            seven_zip  $ kitchen converge #works flawlessly  $ kitchen list                                                                                         Instance             Driver   Provisioner  Verifier  Transport  Last Action  Last Error  default-ubuntu-1404  Vagrant  ChefZero     Inspec    Ssh        Converged    <None>  

Here are the versions, I am using:

$ chef --version                                                                                        Chef Development Kit Version: 1.1.16  chef-client version: 12.17.44  delivery version: master (83358fb62c0f711c70ad5a81030a6cae4017f103)  berks version: 5.2.0  kitchen version: 1.14.2  

Questions

  1. I am able to fix the error but I don't understand "why" this error occurred.I think this is related to chef_repo_path but don't really understand it. so if can explain or point to relevant docs?
  2. Should I be vendoring the cookbooks into ./cookbooks instead of ./cookbooks/chef_rails/berks-cookbooks/. if yes, then how do I make berks vendor do that?
  3. After development, For uploading to github. should include the vendored cookbooks in the repo as well? Planning to use these cookbooks with Chef Server to setup server for rails.

DEPRECATION WARNING: You didn't set config.secret_key_base. Read the upgrade documentation to learn more about this new config option

Posted: 31 Dec 2016 10:42 PM PST

My Rails version is Rails 4.0.13

I have my secret key in config/initializers/secret_token.rb, so I am not sure why it is still throwing this error.

Sprockets::FileNotFound in Projects#index

Posted: 31 Dec 2016 11:41 PM PST

I cloned this project . Then i ran docker-compose up and navigated to localhost:300 and got Sprockets::FileNotFound in Projects#index error. Do I have to do bower install in the host os? Is there a way to do that without having to install node or ruby in the host os? I do not want to pollute my host os thats why i chose docker for my dev environment

Pass parameter to bootstrap modal

Posted: 31 Dec 2016 07:41 PM PST

I have the following link_to on my home page, which opens up a bootstrap modal:

<%= link_to "Message Us", new_message_path, data: { toggle: "modal", target: "#message-modal" }, remote: true %>  

I want to pass a parameter, called packages, to the modal so I can conditionalize some text in the modal and store the value in a hidden input field.

Do I just append the parameter to the path (e.g. new_message_path(package: "1")), pass it as a separate attribute, or something else?

Thanks!

CKEditor: how to use drop down menu with options

Posted: 01 Jan 2017 01:24 AM PST

I implemented CKEditor in my Ruby on Rails app and now I could format text and use links: CKEditor: how to get clcikable links

Can I use CKEditor to get drop down menu with options?

For ex. User provides 4 pictures with numbers: # 1,2,3,4 for each of them and he or she would like to know what is the best pictures? Pictures are downloading separately and this downloading is not connected with CKEditor.

Users using CKEditor, should use drop down menu to check which picture(#1 or 2 or 3 or 4) they like the most.

If, for ex. more users choose #3, then #3 picture is considered the best one.

I think that need to use html to get drop down menu and programming tools (loop, conditions) to estimate what picture is the best.

Is it possible to get drop down menu with the checked choice to inform users what pictures is the best(got more voters), and if so, how to accomplish this task? thanks.

Random ActiveRecord::StatementInvalid errors on Rails 4 app on Heroku

Posted: 31 Dec 2016 05:53 PM PST

My Rails 4 app works fine locally, and also when it's deployed to Heroku in production mode... until I access the app from a second client... then after a few clicks I start getting the following strange sequence of errors (see below).

The exact number of clicks varies a little but it always happens eventually... and but only after a request from a second client. For example, if I restart the app and only play with it on my phone nothing happens. But as soon as I load a couple pages from my laptop... crash

Errors

NOTE: These screenshots are with RAILS_ENV=development so that the actual errors appear.

enter image description here

enter image description here

enter image description here

enter image description here

I'm not sure if I'm understanding these errors correctly, but it looks like ? is not getting properly substituted in the query.

Environment details

  • Rails 4.2
  • hosted on Heroku
  • Ruby 2.2.x
  • MySQL (via ClearDB add-on)

My Gemfile:

source 'https://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.3'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  # See https://github.com/sstephenson/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  gem 'turbolinks', '~> 2.3.0'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc  gem 'devise'  gem "paperclip"  gem 'aws-sdk'  gem 'dotenv-rails', :groups => [:development, :test]  gem 'foundation-rails'  # Access an IRB console on exception pages or by using <%= console %> in views  gem 'web-console', '~> 2.0', group: :development  gem 'mysql'  gem 'rails_12factor', group: :production  gem 'puma'  group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug'    # Use sqlite3 as the database for Active Record    gem 'sqlite3'        # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end  

Here's my Procfile:

web: bundle exec puma -t 5:5 -p ${PORT:-3000} -e ${RACK_ENV:-development}  

Here's my database.yml

# SQLite version 3.x  #   gem install sqlite3  #  #   Ensure the SQLite 3 gem is defined in your Gemfile  #   gem 'sqlite3'  #  default: &default    adapter: sqlite3    pool: 5    timeout: 5000    development:    <<: *default    database: db/development.sqlite3    # Warning: The database defined as "test" will be erased and  # re-generated from your development database when you run "rake".  # Do not set this db to the same as development or production.  test:    <<: *default    database: db/test.sqlite3    production:    url: <%= ENV['DATABASE_URL'] %>  

Here's config/production.rb:

Rails.application.configure do    # Settings specified here will take precedence over those in config/application.rb.      # Code is not reloaded between requests.    config.cache_classes = true      # Eager load code on boot. This eager loads most of Rails and    # your application in memory, allowing both threaded web servers    # and those relying on copy on write to perform better.    # Rake tasks automatically ignore this option for performance.    config.eager_load = true      # Full error reports are disabled and caching is turned on.    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true      # Enable Rack::Cache to put a simple HTTP cache in front of your application    # Add `rack-cache` to your Gemfile before enabling this.    # For large-scale production use, consider using a caching reverse proxy like    # NGINX, varnish or squid.    # config.action_dispatch.rack_cache = true      # Disable serving static files from the `/public` folder by default since    # Apache or NGINX already handles this.    config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?      # Compress JavaScripts and CSS.    config.assets.js_compressor = :uglifier    # config.assets.css_compressor = :sass      # Do not fallback to assets pipeline if a precompiled asset is missed.    config.assets.compile = false      # Asset digests allow you to set far-future HTTP expiration dates on all assets,    # yet still be able to expire them through the digest params.    config.assets.digest = true      # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb      # Specifies the header that your server uses for sending files.    # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache    # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX      # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.    # config.force_ssl = true      # Use the lowest log level to ensure availability of diagnostic information    # when problems arise.    config.log_level = :debug      # Prepend all log lines with the following tags.    # config.log_tags = [ :subdomain, :uuid ]      # Use a different logger for distributed setups.    # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)      # Use a different cache store in production.    # config.cache_store = :mem_cache_store      # Enable serving of images, stylesheets, and JavaScripts from an asset server.    # config.action_controller.asset_host = 'http://assets.example.com'      # Ignore bad email addresses and do not raise email delivery errors.    # Set this to true and configure the email server for immediate delivery to raise delivery errors.    # config.action_mailer.raise_delivery_errors = false      # Enable locale fallbacks for I18n (makes lookups for any locale fall back to    # the I18n.default_locale when a translation cannot be found).    config.i18n.fallbacks = true      # Send deprecation notices to registered listeners.    config.active_support.deprecation = :notify      # Use default logging formatter so that PID and timestamp are not suppressed.    config.log_formatter = ::Logger::Formatter.new      # Do not dump schema after migrations.    config.active_record.dump_schema_after_migration = false      config.serve_static_files = true      config.paperclip_defaults = {      storage: :s3,      s3_credentials: {        bucket: ENV.fetch('S3_BUCKET'),        access_key_id: ENV.fetch('ACCESS_KEY_ID'),        secret_access_key: ENV.fetch('SECRET_ACCESS_KEY'),        s3_region: ENV.fetch('S3_REGION'),        s3_host_name: 's3-us-west-2.amazonaws.com'      }    }      end  

Things I tried:

  • restarting all dynos (works for a minute but then problem comes back)
  • switching to gem mysql2 (couldn't even get this running)
  • switching to gem puma (following this documentation
  • connecting to DB using client (everything seems to work fine)
  • confirmed that the parameters of the request are correct a la this question (the request params look fine)
  • Reading this Heroku / Rails 4 documentation many times

Similar questions that didn't solve my problem

guard-rails mysteriously restarting

Posted: 31 Dec 2016 05:17 PM PST

I upgraded from rails-4.2.7.1 to 5.0.1, now when I run guard it restarts for some reason...

» bundle exec guard  Expected string default value for '--listen-on'; got false (boolean)  17:57:54 - INFO - Bundle already up-to-date  17:57:54 - INFO - [Guard::Rails] will start the default web server on port 3000 in development.  17:57:54 - INFO - Starting Rails...  DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at /home/istrasci/dev/rails/credalizer/config/application.rb:9)  => Booting Puma  => Rails 5.0.1 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  Puma starting in single mode...  * Version 3.6.2 (ruby 2.3.3-p222), codename: Sleepy Sunday Serenity  * Min threads: 5, max threads: 5  * Environment: development  * Listening on tcp://localhost:3000  Use Ctrl-C to stop  17:58:03 - INFO - Rails started, pid 9732  17:58:03 - INFO - Guard::RSpec is running  17:58:03 - INFO - [Guard::Yard] Stopping YARD Documentation Server.  17:58:03 - INFO - [Guard::Yard] Starting YARD Documentation Server.  17:58:03 - INFO - LiveReload is waiting for a browser to connect.  >> YARD 0.9.5 documentation server at http://localhost:8808  Puma starting in single mode...  * Version 3.6.2 (ruby 2.3.3-p222), codename: Sleepy Sunday Serenity  * Min threads: 5, max threads: 5  * Environment: development  * Listening on tcp://0.0.0.0:8808  Use Ctrl-C to stop  17:58:04 - INFO - [Guard::Yard] Server successfully started.  * Restarting...     <------------------------------------------- HERE  17:58:06 - INFO - Guard is now watching at '/home/istrasci/dev/rails/credalizer'  [1] guard(main)> DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at /home/istrasci/dev/rails/credalizer/config/application.rb:9)  => Booting Puma  => Rails 5.0.1 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  A server is already running. Check /home/istrasci/dev/rails/credalizer/tmp/pids/development.pid.  Exiting  

Then I have to manually delete this tmp/pids/development.pid file. My guard-rails worked fine in Rails 4. Anyone know why this is happening?


Here's my Guardfile

notification :gntp if RUBY_PLATFORM =~ /darwin/i  notification :libnotify if RUBY_PLATFORM =~ /linux/i    guard :bundler do    watch('Gemfile')  end    guard 'rails' do    watch('Gemfile.lock')    watch(%r{^(config|lib)/.*})  end    guard :rspec, cmd: 'bin/rspec' do    watch(%r{^spec/.+_spec\.rb$})    watch(%r{^lib/(.+)\.rb$})     { |m| "spec/lib/#{m[1]}_spec.rb" }    watch('spec/spec_helper.rb')  { "spec" }      # Rails example    watch(%r{^app/(.+)\.rb$})                           { |m| "spec/#{m[1]}_spec.rb" }    watch(%r{^app/(.*)(\.erb|\.haml|\.slim)$})          { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }    watch(%r{^app/controllers/(.+)_(controller)\.rb$})  { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }    watch(%r{^spec/support/(.+)\.rb$})                  { "spec" }    watch('config/routes.rb')                           { "spec/routing" }    watch('app/controllers/application_controller.rb')  { "spec/controllers" }    watch('spec/rails_helper.rb')                       { "spec" }      # FactoryGirl factory files    begin      require 'active_support/inflector'      watch(%r{^spec/factories/(.+)\.rb$})      { |m| "spec/models/#{m[1].singularize}_spec.rb" }      watch(%r{^spec/factories/document_data.rb}) { |m| "spec/models/document_data_spec.rb" }    rescue LoadError    end      # Capybara features specs    watch(%r{^app/views/(.+)/.*\.(erb|haml|slim)$})     { |m| "spec/features/#{m[1]}_spec.rb" }      # Turnip features and steps    watch(%r{^spec/acceptance/(.+)\.feature$})    watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$})   { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }  end    guard 'livereload' do    watch(%r{app/views/.+\.(erb|haml|slim)$})    watch(%r{^app/assets/.+\.(s?css|js)})    watch(%r{app/helpers/.+\.rb})    watch(%r{public/.+\.(css|js|html)})    watch(%r{config/locales/.+\.yml})    # Rails Assets Pipeline    watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html|png|jpg))).*}) { |m| "/assets/#{m[3]}" }  end    guard 'yard' do    watch(%r{app/.+\.rb})    watch(%r{lib/.+\.rb})    watch(%r{ext/.+\.c})  end  

Rails Ajax 'Uphold/Like' Button doesn't work

Posted: 01 Jan 2017 03:36 AM PST

I can't figure out why my 'Uphold(Like)' button doesn't work.

My app is a kind of Q&A web site, named 'KnowledgeSprout'. And I appended 'like' feature, named 'uphold', like StackOverFlow's useful button.

The code are below. It look like counting up is working, but the image can't turn to red dynamically.

UpholdController.rb

class UpholdsController < ApplicationController    def create      @uphold = Uphold.create(user_id: current_user.id, knowledge_sprout_id: param  s[:knowledge_sprout_id], answer_id: params[:answer_id], review_id: params[:revie  w_id], product_review_id: params[:product_review_id])      @knowledge_sprouts = KnowledgeSprout.find(params[:knowledge_sprout_id])    end  end  

And KnowledgeSproutController.rb

class KnowledgeSproutsController < ApplicationController      def show      @knowledge_sprout = KnowledgeSprout.find_by(id: params[:id])      @q = Restaurant.ransack(params[:q])      if params[:q].present?        @restaurants = @q.result(distinct: true).page(params[:page])      end      @answers = Answer.where(ks_id: params[:id])      @answer = Answer.new      ahoy.track "ks_show", id:  params[:id]    end  end  

Here's knowledege_sprout.html.slim

.upholds    = render partial: "uphold", locals: {knowledge_sprout: @knowledge_sprout}  

_uphold.html.slim

  - if user_signed_in?      - if @knowledge_sprout.uphold_user(current_user.id)        = image_tag("icon_red_heart.png")        span          = @knowledge_sprout.upholds_count      - else        = button_to knowledge_sprout_upholds_path(@knowledge_sprout.id), id: "uphold-button", remote: true do          = image_tag("icon_heart.png")          span            = @knowledge_sprout.upholds_count    - else      - if @knowledge_sprout.uphold_user(current_user.id)        = image_tag("icon_red_heart.png")        span          = @knowledge_sprout.upholds_count      - else        = image_tag("icon_heart.png")        span          = @knowledge_sprout.upholds_count  

JS

$("#uphold-button").on("ajax:success", (e, data, status, xhr) ->    $("#uphold-button").html("= j(render partial: 'uphold', locals: { knowledge_sprout: @knowledge_sprout})")    alert "hohoho"  ).on "ajax:error", (e, xhr, status, error) ->    $("#uphold-button").append "<p>ERROR</p>"  

Here's Models.

class KnowledgeSprout < ActiveRecord::Base          belongs_to :user          has_many :upholds, dependent: :destroy            def uphold_user(user_id)            upholds.find_by(user_id: user_id)          end            attr_accessor :file  end  class Uphold < ActiveRecord::Base    belongs_to :knowledge_sprout, counter_cache: :upholds_count    belongs_to :answers, counter_cache: :upholds_count    belongs_to :reviews, counter_cache: :upholds_count    belongs_to :product_reviews, counter_cache: :upholds_count    belongs_to :user  end   

Also here's rake routes results.

     knowledge_sprout_upholds POST     (/:locale)/knowledge_sprouts/:knowledge_sprout_id/upholds(.:format)     upholds#create {:locale=>/en|ja/}        knowledge_sprout_uphold DELETE   (/:locale)/knowledge_sprouts/:knowledge_sprout_id/upholds/:id(.:format) upholds#destroy {:locale=>/en|ja/}                                GET      (/:locale)/knowledge_sprouts(.:format)                                  knowledge_sprouts#index {:locale=>/en|ja/}                                POST     (/:locale)/knowledge_sprouts(.:format)                                  knowledge_sprouts#create {:locale=>/en|ja/}                                GET      (/:locale)/knowledge_sprouts/new(.:format)                              knowledge_sprouts#new {:locale=>/en|ja/}                                GET      (/:locale)/knowledge_sprouts/:id/edit(.:format)                         knowledge_sprouts#edit {:locale=>/en|ja/}                                GET      (/:locale)/knowledge_sprouts/:id(.:format)                              knowledge_sprouts#show {:locale=>/en|ja/}                                PATCH    (/:locale)/knowledge_sprouts/:id(.:format)                              knowledge_sprouts#update {:locale=>/en|ja/}                                PUT      (/:locale)/knowledge_sprouts/:id(.:format)                              knowledge_sprouts#update {:locale=>/en|ja/}                                DELETE   (/:locale)/knowledge_sprouts/:id(.:format)                              knowledge_sprouts#destroy {:locale=>/en|ja/}  

Any idea? Help me pls... Thanks in advance.

Unable to seed JSON file into db table Rails 5

Posted: 31 Dec 2016 04:55 PM PST

I am having trouble seeding the FDA drug event data into my Rails 5 database. What would I like to do is recreate the table from the JSON file and serve the data directly from my own API. The issue may revolve around missing table attributes that I may have overlooked while building the table. I'm reading the API documentation on openFDA Drug Events Reference

I will post my code below.

Error:

 ActiveRecord::MultiparameterAssignmentErrors: 1 error(s) on assignment of multiparameter attributes [error on assignment [["results"]] to ["results", [{"receivedate"=>"20050719", "patient"=>{"reaction"=>[{"reactionmeddrapt"=>"GASTRIC ULCER HAEMORRHAGE"}], "patientsex"=>"2", "drug"=>[{"medicinalproduct"=>"CELEBREX", "drugadministrationroute"=>"048", "drugdosagetext"=>"ORAL", "openfda"=>{"manufacturer_name"=>["G.D. Searle LLC Division of Pfizer Inc"], "unii"=>["JCX84Q7J1L"], "product_type"=>["HUMAN PRESCRIPTION DRUG"], "rxcui"=>["349514", "686381", "686379", "213468", "213469", "352314", "205323", "205322"], "spl_set_id"=>["8d52185d-421f-4e34-8db7-f7676db2a226"], "route"=>["ORAL"], "generic_name"=>["CELECOXIB"], "brand_name"=>["CELEBREX"], "pharm_class_cs"=>["Nonsteroidal Anti-inflammatory Compounds [Chemical/Ingredient]"], "product_ndc"=>["0025-1525", "0025-1515", "0025-1520", "0025-1530"], "pharm_class_epc"=>["Nonsteroidal Anti-inflammatory Drug [EPC]"], "substance_name"=>["CELECOXIB"], "spl_id"=>["9700ec8e-dde6-46fe-8ada-349b9c1660ff"], "pharm_class_moa"=>["Cyclooxygenase Inhibitors [MoA]"], "application_number"=>["NDA020998"], "nui"=>["N0000000160", "N0000175722", "N0000175721"], "package_ndc"=>["0025-1520-34", "0025-1520-31", "0025-1515-01", "0025-1525-34", "0025-1530-01", "0025-1525-31", "0025-1530-02", "0025-1520-51", "0025-1525-51"]}, "drugcharacterization"=>"1", "drugauthorizationnumb"=>"20998"}]}, "sender"=>{"senderorganization"=>"FDA-Public Use"}, "transmissiondate"=>"20060218", "fulfillexpeditecriteria"=>"2", "receiptdate"=>"20040524", "transmissiondateformat"=>"102", "receiptdateformat"=>"102", "primarysource"=>{"reportercountry"=>"UNITED STATES", "qualification"=>"5"}, "seriousnesshospitalization"=>"1", "receiver"=>nil, "serious"=>"1", "receivedateformat"=>"102", "companynumb"=>"2004214868US", "safetyreportid"=>"4722984-4"}, {"receivedate"=>"20050719", "receiptdate"=>"20040622", "patient"=>{"reaction"=>[{"reactionmeddrapt"=>"GLAUCOMA"}], "patientonsetage"=>"70", "patientsex"=>"2", "patientonsetageunit"=>"801", "drug"=>[{"medicinalproduct"=>"CELEBREX", "drugindication"=>"ARTHRITIS", "drugadministrationroute"=>"048", "drugdosagetext"=>"200 MG, QD, ORAL", "openfda"=>{"manufacturer_name"=>["G.D. Searle LLC Division of Pfizer Inc"], "unii"=>["JCX84Q7J1L"], "product_type"=>["HUMAN PRESCRIPTION DRUG"], "rxcui"=>["349514", "686381", "686379", "213468", "213469", "352314", "205323", "205322"], "spl_set_id"=>["8d52185d-421f-4e34-8db7-f7676db2a226"], "route"=>["ORAL"], "generic_name"=>["CELECOXIB"], "brand_name"=>["CELEBREX"], "pharm_class_cs"=>["Nonsteroidal Anti-inflammatory Compounds [Chemical/Ingredient]"], "product_ndc"=>["0025-1525", "0025-1515", "0025-1520", "0025-1530"], "pharm_class_epc"=>["Nonsteroidal Anti-inflammatory Drug [EPC]"], "substance_name"=>["CELECOXIB"], "spl_id"=>["9700ec8e-dde6-46fe-8ada-349b9c1660ff"], "pharm_class_moa"=>["Cyclooxygenase Inhibitors [MoA]"], "application_number"=>["NDA020998"], "nui"=>["N0000000160", "N0000175722", "N0000175721"], "package_ndc"=>["0025-1520-34", "0025-1520-31", "0025-1515-01", "0025-1525-34", "0025-1530-01", "0025-1525-31", "0025-1530-02", "0025-1520-51", "0025-1525-51"]}, "drugcharacterization"=>"1", "drugauthorizationnumb"=>"20998"}]}, "sender"=>{"senderorganization"=>"FDA-Public Use"}, "transmissiondate"=>"20060218", "primarysource"=>{"reportercountry"=>"UNITED STATES", "qualification"=>"5"}, "seriousnessother"=>"1", "transmissiondateformat"=>"102", "receiptdateformat"=>"102", "receiver"=>nil, "serious"=>"1", "receivedateformat"=>"102", "fulfillexpeditecriteria"=>"2", "safetyreportid"=>"4723089-9", "companynumb"=>"2004220463US"}, {"receivedate"=>"20050721", "patient"=>{"reaction"=>[{"reactionmeddrapt"=>"FATIGUE"}], "patientonsetage"=>"40", "patientsex"=>"2", "patientonsetageunit"=>"801", "drug"=>[{"medicinalproduct"=>"AVANDIA", "drugadministrationroute"=>"048", "drugdosagetext"=>"4MG TWICE PER DAY", "drugtreatmentduration"=>"3", "openfda"=>{"manufacturer_name"=>["GlaxoSmithKline LLC"], "product_type"=>["HUMAN PRESCRIPTION DRUG"], "rxcui"=>["261242", "261241", "312859", "312860"], "spl_set_id"=>["ec682aec-e98f-41a1-9d21-eb7580ea3a8a"], "route"=>["ORAL"], "generic_name"=>["ROSIGLITAZONE MALEATE"], "brand_name"=>["AVANDIA 4MG", "AVANDIA 2MG"], "product_ndc"=>["0173-0863", "0173-0861"], "substance_name"=>["ROSIGLITAZONE MALEATE"], "spl_id"=>["0af0d2fb-2525-4739-99b3-ef58f7251f1a"], "application_number"=>["NDA021071"], "package_ndc"=>["0173-0861-18", "0173-0863-13"]}, "drugtreatmentdurationunit"=>"802", "drugcharacterization"=>"1", "drugauthorizationnumb"=>"021071"}, {"drugcharacterization"=>"2", "medicinalproduct"=>"CAPOZIDE"}]}, "sender"=>{"senderorganization"=>"FDA-Public Use"}, "transmissiondate"=>"20060218", "primarysource"=>{"reportercountry"=>"UNITED STATES", "qualification"=>"5"}, "receiptdate"=>"20040618", "transmissiondateformat"=>"102", "receiptdateformat"=>"102", "receiver"=>nil, "serious"=>"2", "receivedateformat"=>"102", "fulfillexpeditecriteria"=>"2", "safetyreportid"=>"4719690-9", "companynumb"=>"US-GLAXOSMITHKLINE-A0515241A"}, {"receivedate"=>"20050719", "patient"=>{"reaction"=>[{"reactionmeddrapt"=>"CHOLELITHIASIS"}], "patientsex"=>"1", "drug"=>[{"medicinalproduct"=>"CELEBREX", "drugindication"=>"UPPER LIMB FRACTURE", "drugdosagetext"=>"200 MG", "drugtreatmentduration"=>"14", "openfda"=>{"manufacturer_name"=>["G.D. Searle LLC Division of Pfizer Inc"], "unii"=>["JCX84Q7J1L"], "product_type"=>["HUMAN PRESCRIPTION DRUG"], "rxcui"=>["349514", "686381", "686379", "213468", "213469", "352314", "205323", "205322"], "spl_set_id"=>["8d52185d-421f-4e34-8db7-f7676db2a226"], "route" =>"UNITED STATES", "qualification"=>"5"}, "seriousnesshospitalization"=>"1", "receiver"=>nil, "serious"=>"1", "receivedateformat"=>"102", "companynumb"=>"2004217335US", "safetyreportid"=>"4723050-4"}, {"receivedate"=>"20050729", "patient"=>{"reaction"=> for #<AdvDrugEvent:0x18b71b00>)]  

Database Table Schema

create_table "adv_drug_events", force: :cascade do |t|      t.string   "safetyreport"      t.string   "safetyreportversion"      t.string   "receivedate"      t.string   "receivedateformat"      t.string   "serious"      t.string   "seriousnessdeath"      t.string   "seriousnessdisabling"      t.string   "seriousnesshospitalization"      t.string   "seriousnesslifethreatening"      t.string   "seriousnessother"      t.string   "transmissiondate"      t.string   "transmissiondateformat"      t.string   "duplicate"      t.string   "companynumb"      t.string   "occurcountry"      t.string   "primarysourcecountry"      t.string   "primarysource"      t.string   "reportduplicate"      t.string   "sender"      t.string   "receiver"      t.datetime "created_at",                 null: false      t.datetime "updated_at",                 null: false      t.date     "last_updated"      t.string   "terms"    end  

ruby on rails, I cant run my test because my rake test keeps on getting aborted

Posted: 31 Dec 2016 04:11 PM PST

when I run rake test i get the following error:

[NOTE] You may have encountered a bug in the Ruby interpreter or extension libraries. Bug reports are welcome. For details: http://www.ruby-lang.org/bugreport.html

Aborted

I got 3 controllers in my application and two of them are models.

This is my clients controller test:

require 'test_helper'    class ClientsControllerTest < ActionController::TestCase    setup do      @client = clients(:one)    end      test "should get index" do      get :index      assert_response :success      assert_not_nil assigns(:clients)    end      test "should get new" do      get :new      assert_response :success    end      test "should create client" do      assert_difference('Client.count') do        post :create, client: { name: @client.name, email: @client.email + "create" }      end        assert_redirected_to client_path(assigns(:client))    end      test "should show client" do      get :show, id: @client      assert_response :success    end      test "should get edit" do      get :edit, id: @client      assert_response :success    end      test "should update client" do      patch :update, id: @client, client: { name: @client.name }      assert_redirected_to client_path(assigns(:client))    end      test "should destroy client" do      assert_difference('Client.count', -1) do        delete :destroy, id: @client      end        assert_redirected_to clients_path    end  end  

project controller tests:

require 'test_helper'    class ProjectsControllerTest < ActionController::TestCase    setup do      @project = projects(:one)      @client = clients(:one)    end      test "should get index" do      get :index      assert_response :success      assert_not_nil assigns(:projects)    end      test "should get new" do      get :new      assert_response :success    end      test "should create project" do      assert_difference('Project.count') do        post :create, project: { client_id: @client, project_description: @project.project_description, project_timescale: @project.project_timescale, title: @project.title }      end        assert_redirected_to project_path(assigns(:project))    end      test "should show project" do      get :show, id: @project      assert_response :success    end      test "should get edit" do      get :edit, id: @project      assert_response :success    end      test "should update project" do      patch :update, id: @project, project: { client_id: @project.client_id, project_description: @project.project_description, project_timescale: @project.project_timescale }      assert_redirected_to project_path(assigns(:project))    end      test "should destroy project" do      assert_difference('Project.count', -1) do        delete :destroy, id: @project      end        assert_redirected_to projects_path    end  end  

Index controller test:

require 'test_helper'    class IndexControllerTest < ActionController::TestCase    test "should get index" do      get :index      assert_response :success    end      test "should get contact"  do       get :contact       assert_response:success        assert_template layout: 'application'        assert_select'title', 'My Notes'      assert_select'h1', 'Contact Us'       assert_select 'p', 'Complete the following form to get in touch with us.'       end    end  

client model test:

require 'test_helper'    class ClientTest < ActiveSupport::TestCase    # test "the truth" do    #   assert true    # end      #tests to see if an empty client can be created    test "no empty clients!" do      client = Client.new      client.save        refute client.valid?    end      #checks if a valid client can be created    test "should save valid clients" do      client = Client.new        client.name = "David"      client.email = "example@gmail.com"        client.save      assert client.valid?    end      test "no duplicate emails" do        client1 = Client.new      client1.name = "David"      client1.email = "example@gmail.com"      client1.save      assert client.valid?        client2 = Client.new      client2.name = "David"      client2.email = "example@gmail.com"      client2.save      refute client.valid?    end    end  

project model test:

require 'test_helper'    class ProjectTest < ActiveSupport::TestCase    # test "the truth" do    #   assert true    # end      setup do      @client = clients(:one)    end      test "no empty projects" do       project = Project.new      project.save        refute project.valid?    end        test "make valid projects" do      project = Project.new        project.title = "first project"      project.project_description = "building a forum for a game clan"      project.project_timescale = "1 month"        project.save      assert project.valid?    end  end  

clients.yml :

# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html    one:    name: MyString    email: MyText1    two:    name: MyString    email: MyText2  

projects.yml:

# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html    one:    client: one    project_description: MyText    project_timescale: MyString    title: MyString    two:    client: two    project_description: MyText    project_timescale: MyString    title: MyString  

Cloud9 won't deploy to Heroku

Posted: 31 Dec 2016 03:49 PM PST

Hey I'm in an online boot camp and I need to deploy my app to Heroku and I'm using the Cloud9 IDE but every time I go to the page it says it doesn't exist even though I followed the instructions. https://github.com/weredre/achievement3

Calculating a simple decimal in rails console using postgresql

Posted: 31 Dec 2016 04:01 PM PST

Ok...I think I'm missing something very obvious here but haven't been able to google myself through this solution. I have two simple rails methods that calculate the number of up votes and down votes. They will always return a fraction because i'm trying to show a percentage (up_vote_count / votal_vote_count). I open the rails console and run the following:

y = @somespecificrecord  

then...

y.up_vote_count  

This returns 1 as is expected

y.down_vote_count  

This returns 1 as is expected

y.total_vote_count  

This returns 2 as is expected.

However, when I run in the console...

y.up_vote_count / y.total_vote_count

This returns 0 when it should return .50. I've been reading about floats/integers/decimals, etc and I do see this in the schema on the model i'm working from:

t.float "value", default: 0.0  

Is this my problem?...and if so what do I have to do to allow myself to do a simple formula like the one above in rails console that will return the correct decimal rounded to 2 digits (i.e, .50 in this case above). I don't know if I want to run any migrations to change data types because this is a gem (& as a beginner I tend to stay away from customizing code from any gems I'm using). Is there another way? something small i'm missing hopefully?

UPDATE: I'm learning decimals are slower than floats also, so is there any way to accomplish this with continuing to use t.float "value", default: 0.0

thanks for any help.

ActionCable issues on app upgraded to Rails 5

Posted: 31 Dec 2016 04:04 PM PST

ActionCable is not working on my app that I just upgraded to Rails 5.0.1. I generated a channel with rails g channel.

When I run the server I don't see any line in the log that indicates ActionCable is doing anything. On the client side I get App is not defined

I created a new app with rails new and ActionCable works fine in it. I compared all the relevant files in and they look the same in both apps.

Are there some gems that I need to install in my upgraded app that would be installed by default in a new Rails 5 app? I checked and I have actioncable.