Thursday, April 7, 2016

Ruby on rails or Laravel | Fixed issues

Ruby on rails or Laravel | Fixed issues


Ruby on rails or Laravel

Posted: 07 Apr 2016 07:48 AM PDT

I am a Web Developer and I am in a middle of a dilemma. I have worked till now with different CMS mostly with Wordpress and Joomla but also Umbraco. Recently i have collaborated i 2 projects with my friend and we have developed them in Laravel framework. Im good at html and css he is on backend. My purpose is to be a Full Stack developer because i feel good also on backend and im trying to make a solution in which framework should i focus to learn more and improve my skills. As i said i have used Laravel and i liked. For Ruby on Rails i have heard and read information that because it is an old and stable MVC framework is better to work with that. I would like to hear a professional opinion in which framework should i focus. Notice that i dont know Ruby. Php i have practices but not a pro.

Conditional Uniqueness Constraint Ruby on rails

Posted: 07 Apr 2016 07:47 AM PDT

I have following model level uniqueness constraint and need to move same to MySQL level. What is the SQL statement to do same.

class Blog < ActiveRecord::Base    validate :uniqness_of_title      def uniqness_of_title        blog = Blog.where("title=? and lock_version<>-1", self.title).last        self.errors.add :base, "Title already exists." if blog    end  end  

Rails and Puma server - cannot run localhost:3000 - only a white empty page is rendered

Posted: 07 Apr 2016 07:20 AM PDT

I am using Rails 4.2.6 and Ruby 2.3.0 and Puma 3.3.0 During the last couple days I ran some bundle update and after rails s all browsers for the same URL localhost:3000 are rendering the same blank page. This is consistent for all 6-7 applications I am playing with. However all are working in "production" when deployed to Heroku. Seems to be only a matter related to my dev env.

Don't know how to solve this. Any help will be much appreciated. Can't continue development if can't run unit tests on the code I am developing.

However all works well when I am using another port. For example when starting the app server with the command rails s -p 3001 or port 3002 I have no problems to run the apps in any browser using the URL localhost:3001 or localhost:3002.

What is wrong with my 3000 port or Puma or both?

Ruby on rails curl -k -u

Posted: 07 Apr 2016 07:25 AM PDT

I am trying to do the equivalent of

 curl -u username -k https://my-site.com  

So far I have benn following http://ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html. I have tried:

uri = URI('https://my-site.com')    Net::HTTP.start(uri.host, uri.port,                  :use_ssl => uri.scheme == 'https') do |http|    request = Net::HTTP::Get.new uri      response = http.request request # Net::HTTPResponse object  end  

I am getting SSL errors. I can curl it in the terminal. Not sure how to supply a password and username

req.basic_auth 'user', 'password'  

didn't help.

Errors I am getting:

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed  

Any pointers would be appreciated.

Rails 4 Capistrano deployment cannot find activesupport

Posted: 07 Apr 2016 07:30 AM PDT

I am trying to deploy from my local machine to my deployment server via Capistrano. When I deploy, it connects to the server then dumps out the following information.

** sftp upload /var/folders/x0/hyzt7pms0599ymtyjft739kw0000gn/T/20160406223514.tar.gz -> /tmp/20160406223514.tar.gz      [address] /tmp/20160406223514.tar.gz      [address] done    * sftp upload complete    * executing "cd /var/www/address/releases && tar xzf /tmp/20160406223514.tar.gz && rm /tmp/20160406223514.tar.gz"      servers: ["address"]      [address] executing command      command finished in 519ms    * 2016-04-06 18:35:59 executing `deploy:finalize_update'      triggering before callbacks for `deploy:finalize_update'    * 2016-04-06 18:35:59 executing `deploy:assets:symlink'    * executing "rm -rf /var/www/address/releases/20160406223514/public/assets && mkdir -p /var/www/address/releases/20160406223514/public && mkdir -p /var/www/address/shared/assets && ln -s /var/www/address/shared/assets /var/www/address/releases/20160406223514/public/assets"      servers: ["server"]      [server] executing command      command finished in 48ms    * executing "chmod -R -- g+w /var/www/address/releases/20160406223514 && rm -rf -- /var/www/address/releases/20160406223514/public/system && mkdir -p -- /var/www/address/releases/20160406223514/public/ && ln -s -- /var/www/address/shared/system /var/www/address/releases/20160406223514/public/system && rm -rf -- /var/www/address/releases/20160406223514/log && ln -s -- /var/www/address/shared/log /var/www/address/releases/20160406223514/log && rm -rf -- /var/www/address/releases/20160406223514/tmp/pids && mkdir -p -- /var/www/address/releases/20160406223514/tmp/ && ln -s -- /var/www/address/shared/pids /var/www/address/releases/20160406223514/tmp/pids"      servers: ["address"]      [address] executing command      command finished in 49ms      triggering after callbacks for `deploy:update_code'    * 2016-04-06 18:35:59 executing `deploy:assets:precompile'      triggering before callbacks for `deploy:assets:precompile'    * 2016-04-06 18:35:59 executing `deploy:assets:update_asset_mtimes'    * executing "[ -e '/var/www/address/shared/assets/.sprockets-manifest*' ] && cat /var/www/address/shared/assets/.sprockets-manifest* || echo"      servers: ["address"]      [server] executing command      command finished in 31ms    * executing "cd -- /var/www/address/releases/20160406223514 && RAILS_ENV=production RAILS_GROUPS=assets rake assets:precompile"      servers: ["address"]      [address] executing command   ** [out :: address] Could not find activesupport-4.2.0 in any of the sources   ** [out :: address] Run `bundle install` to install missing gems.      command finished in 547ms  *** [deploy:update_code] rolling back    * executing "rm -rf /var/www/address/releases/20160406223514; true"      servers: ["address"]      [address] executing command      command finished in 57ms  failed: "sh -c 'cd -- /var/www/address/releases/20160406223514 && RAILS_ENV=production RAILS_GROUPS=assets rake assets:precompile'" on address  

It says that it could not find activesupport, but when I run gem list on the server, it is listed and shows version 4.2.6, 4.2.4, 4.2.0.

This is a permissions problem?

Here is deploy.rb

set :application, "app"  set :repository,  "repo"    set :deploy_to, '/var/www/address'  set :scm, :git  set :branch, "master"    set :user, "user"    set :use_sudo, false    set :rails_env, "production"  set :deploy_via, :copy    set :keep_releases, 5    default_run_options[:pty] = true    server "address", :app, :web, :db, :primary => true      namespace :deploy do      desc "Symlink shared config files"      task :symlink_config_files do          run "#{ try_sudo } ln -s #{ deploy_to }/shared/config/database.yml #{ current_path }/config/database.yml"      end        desc "Restart Passenger app"      task :restart do          run "#{ try_sudo } touch #{ File.join(current_path, 'tmp', 'restart.txt') }"      end  end      after "deploy", "deploy:symlink_config_files"  after "deploy", "deploy:restart"  after "deploy", "deploy:cleanup"  

Rails Simple form array text input

Posted: 07 Apr 2016 07:11 AM PDT

I am using SimpleForm to build my form.

Having a model with two arrays of decimals, weights[] and repetitions[], I used this tutorial to make an input form for each number in these arrays seperately.

My problem is i don't know how to add/remove fields from the form with javascript. The author of the tutorial didn't put any code "because it's rather trivial task". Where and how do i need to put javascript to perform these tasks?

Begginer web development RoR [on hold]

Posted: 07 Apr 2016 07:06 AM PDT

I'm practicing web apps dev on RoR, completely new to this field. Id like to know how can I store some data from one site(user inputs URL) into own database, then search that base by some criteria and display it on on my own site? What would be steps in dev, how to begin? Thanks

Switch from C/C++ embedded domain to Web development

Posted: 07 Apr 2016 07:37 AM PDT

I'm from a C/C++ background having work experience in embedded domain. I would like to switch to Web application development, as it is something new I would like to explore and also to increase my employability. I have a total experience of 9 years.

Also, I'm very much interested to learn Ruby on Rails. Any suggestion on where to start?

Extracting only open issues from github api without any pull request using ruby on rails

Posted: 07 Apr 2016 06:52 AM PDT

I am building an application which should extract all the open issues from any of the directory of github using github-api gem in ROR. The problem is that it is also extracting pull requests from the repository. Is there any way to extract only open issues.

here is the blog from where I am following. here is another

code git = Github.new oauth_token: issues = git.issues.list user: 'Shippable', repo: 'support', state: 'open'

are there any other filter via which only allows open issues to extract.

I want to render my page after downloading the csv files to index

Posted: 07 Apr 2016 06:47 AM PDT

After downloading the CSV file it is showing the empty(white Index) page i need to be refresh the page each time,To get the index page,can any one tell me how to render the page after downloading the csv each time.

class EmployeeExportsController < ApplicationController      def index          @employees = Employee.all.order('id ASC')          @entities = Entity.get_active_entities          @employees = Employee.includes(:entity).all          employee_ids = @employees.map(&:id)          respond_to do |format|              format.html              format.csv { send_data @employees.to_csv }          end      end  end  

Consult replicating values on digit cpf

Posted: 07 Apr 2016 06:25 AM PDT

I have a search that when digit a CPF show all results. Ok, but I need that show this way: (Just a person and the quantity of contracts that it has) * My code is in portuguese, sorry

Name  Registry  CPF     Contract 1 ---- Show all contracts     Contract 2   --------     Contract 3 -----------  

But it is currently coming so: (The same values according to the amount of contract)

Name  Registry  CPF     Contract 1 ---- Show all contracts     Contract 2   --------     Contract 3 -----------    Name  Registry  CPF     Contract 1 ---- Show all contracts     Contract 2   --------     Contract 3 -----------    Name  Registry  CPF     Contract 1 ---- Show all contracts     Contract 2   --------     Contract 3 -----------  

It is replicating values... because contract's number

My view is this:

<% if params[:pesquisa_func_cpf].present? %>    <h4><b>Resultados</b></h4>    <% @autorizacoes.each do |autorizacao| %>      <table class="table table-condensed">        <tr>          <th>Name</th>          <td><%= autorizacao.employee.person.name %></td>        </tr>        <tr>          <th>Registry</th>          <td><%= autorizacao.employee.registry %></td>        </tr>        <tr>          <th>CPF</th>          <td><%= autorizacao.employee.person.cpf %></td>        </tr>      </table>      <hr />      <table class="table table-condensed table-bordered">        <th>Contract number</th>        <% @autorizacoes.each do |autorizacao| %>          <td><%= autorizacao.number_contract %></td>        <% end %>      </table>      <% end %>  <% end%>  

In this is my controller:

if params[:pesquisa_func_cpf].present? @autorizacoes = Autorizacao.pesquisa_func_cpf(params[:pesquisa_func_cpf]).all

I try the .distinct instead of .all, but don't work : (

And my consult (I use oracle), is it:

select * from autorizacoes INNER JOIN employers ON employers.id = autorizacoes.employer_id                             INNER JOIN people ON employers.person_id = people.id                             WHERE people.cpf  LIKE '111.111.111-11'  

And it return 3 results, according my example. Please, how make just leave this structure:

Name  Registry  CPF     Contract 1 ---- Show all contracts     Contract 2   --------     Contract 3 -----------  

Date parsing/converting with AngularJS

Posted: 07 Apr 2016 07:29 AM PDT

I am working on a personal project where I need to get a date using bootstrap-datepicker convert it to UTC and send it to an API formated as one of the ISO8601 formats ("yyy-mm-dd").

I am using Angular in the front and Rails in the backend API. The problem is that as the application will use multiple locales, the date format sent from date-picker to the angular controller will vary, it can be "dd/mm/yyyy" or "mm/dd/yyyy".

How would I be able to make the proper adjustments to send the date to the API independently of the frontend format?

Testing Grape api. ActionController::TestCase @controller is nil

Posted: 07 Apr 2016 06:11 AM PDT

I'm trying to test my grape api and I'm having problems with my test.

I use the rails default test, this is my Gemfile test part.

group :development, :test do    gem 'sqlite3'      gem 'byebug' # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'spring' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'factory_girl_rails'    gem 'capybara'    gem 'selenium-webdriver'    gem 'capybara-angular'    gem 'poltergeist'    gem 'phantomjs', :require => 'phantomjs/poltergeist', platforms: :ruby # linux  end  

My controller :

# app/controllers/api/v1/vehicules.rb  module API    module V1      class Vehicules < Grape::API  

and my test :

# test/controllers/api/v1/vehicules_test.rb  require "test_helper"    class API::V1::VehiculesTest < ActionController::TestCase    @controller = API::V1::VehiculesTest.new      test "GET /api/v1/vehicules?user_id=123" do      get("/api/v1/vehicules?user_id=123")      assert_response :success      json_response = JSON.parse(response.body)      assert_not(json_response['principal'], "principal devrait être faux")    end      test "PUT /api/v1/vehicules?user_id=123" do      put("/api/v1/vehicules?user_id=123", { 'princiapl' => true }, :format => "json")      assert_response :success      json_response = JSON.parse(response.body)      assert_not(json_response['principal'], "principal devrait être vrais")    end    end  

When I launch the test, I got this error :

  1) Error:  API::V1::VehiculesTest#test_GET_/api/v1/vehicules?user_id=123:  RuntimeError: @controller is nil: make sure you set it in your test's setup meth  od.      test/controllers/api/v1/vehicules_test.rb:7:in `block in <class:VehiculesTes  t>'  

I couldn't find why the controller is not found. Do I have to add something in my test_helper.rb ? It contains nothing for ActionController :

class ActionController::TestCase    end  

Addressing backbone 304 not modified issue

Posted: 07 Apr 2016 05:47 AM PDT

I am new to backbone, I am writing a rails app using backbone. When the root page loads backbone renders the page getting results from the api.

router.js file    var Router = Backbone.Router.extend({    routes: {      "": "showActivities",      "activity/:id": "showActivity"      },        showActivities: function() {       var activities = new Activities();     activities.fetch().done(function() {     var indexview = new IndexView({ collection: activties });      $('main').html(indexview.render().el);      });      },      showActivity: function(id) {      }    });  

Activity collection and model

var Activities = Backbone.Collection.extend({    model: Activity,    url: '/api/activities'  });    var Activity = Backbone.Model.extend({      urlRoot: '/api/activities'  });  

activities controller

class Api::ActivitiesController < ApplicationController      def index      if params[:location].nil?        @activities = Activity.all      else        @activities = Activity.near(params[:location], 30)      end        render json: @activites, status: 200    end        def create      @activity = activity.new      @activity.name = params[:name]        @activity.save      render json: @activities, status: 200    end      def show       @activity = Activity.find(params[:id])       render json: @activity, status: 200    end    end  

whenever I load the root page I am not getting any results from the api even though there is data. The network log shows 304 not modified status. I tried changing the fetch by setting cache to false but I am not getting any data from api. Is there anything I am doing wrong? Your feedback is much appreciated. Please let me know if you need more details.

Devise invitable signup date column

Posted: 07 Apr 2016 05:42 AM PDT

I use devise invitable on my rails app, I want to display a sortable column with ransack that displays the date when a user signed up.

A user can create their own account or be invited, when a user is invited the created_at column is updated so it's not the actual date of their signup, how do I combine the created_at column and the invitation_accepted_at column so it can be sorted by ransack to display the date the user signed up to the site?

Error when running rake assets:precompile?

Posted: 07 Apr 2016 05:59 AM PDT

I am in an uneviable situation where I have to deploy a ruby one rail application on a ubuntu server without any documentation and without much experience in ruby (or ruby on rails).

I tried to follow the steps listed out in various forums/tutorials. I have started the WEBricks server on port 80, but the minute I try to access the web application from a browser I get the following not he browser.

couldn't find file './compiled/admin' under '/home/ubuntu/www/my-app/app/assets/stylesheets' with type 'text/css'  

Then someone suggested that I run
rake assets:precompile
When I run this command I get the following error...

    DEPRECATION WARNING: Currently, Active Record suppresses errors raised within `after_rollback`/`after_commit` callbacks and only print them to the logs. In the next version, these errors will no longer be suppressed. Instead, the errors will propagate normally just like in other Active Record callbacks.    You can opt into the new behavior and remove this warning by setting:      config.active_record.raise_in_transactional_callbacks = true     (called from <class:User> at /home/ubuntu/www/my-app/app/models/user.rb:27)  rake aborted!  Sprockets::FileNotFound: couldn't find file './compiled/admin' under '/home/ubuntu/www/my-app/app/assets/stylesheets' with type 'text/css'  /home/ubuntu/www/my-app/app/assets/stylesheets/admin.css:10  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/resolve.rb:64:in `resolve!'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:399:in `resolve'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:207:in `process_require_directive'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:180:in `block in process_directives'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:178:in `each'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:178:in `process_directives'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:83:in `_call'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:68:in `call'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:75:in `call_processor'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:57:in `block in call_processors'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `reverse_each'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `call_processors'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:86:in `load_asset_by_uri'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:45:in `block in load'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:155:in `fetch_asset_from_dependency_cache'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:38:in `load'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:20:in `block in initialize'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:47:in `load'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/bundle.rb:23:in `block in call'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/utils.rb:183:in `dfs'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/bundle.rb:24:in `call'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:75:in `call_processor'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:57:in `block in call_processors'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `reverse_each'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `call_processors'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:86:in `load_asset_by_uri'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:45:in `block in load'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:155:in `fetch_asset_from_dependency_cache'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:38:in `load'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:20:in `block in initialize'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:47:in `load'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/base.rb:63:in `find_asset'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/base.rb:70:in `find_all_linked_assets'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/manifest.rb:130:in `block in find'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/manifest.rb:129:in `each'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/manifest.rb:129:in `find'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/sprockets/manifest.rb:162:in `compile'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-rails-2.3.2/lib/sprockets/rails/task.rb:70:in `block (3 levels) in define'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-3.2.0/lib/rake/sprocketstask.rb:147:in `with_logger'  /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/sprockets-rails-2.3.2/lib/sprockets/rails/task.rb:69:in `block (2 levels) in define'  Tasks: TOP => assets:precompile  (See full trace by running task with --trace)  


Any help will be much appreciated. If you want me to provide any other information please ask.

The following is the app/assets/stylesheets/admin.css file

/*   * Admin stylesheets   *   *= require select2   *= require select2-bootstrap   *= require_tree ./plugins   *= require_tree ./fonts   *   * Pull compiled from /app/assets/stylesheets/compiled   *= require ./compiled/admin   *   */  


The Gemfile looks like this.

source 'https://rubygems.org'    gem 'rails', '4.2.0'  gem 'sass-rails', '~> 5.0.3'  gem 'less-rails', '~> 2.7.0'  gem 'therubyracer'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.1.0'  gem 'jquery-rails'  gem 'sqlite3', group: :development  gem 'pg'    #bootstrap components  gem 'bootstrap-datepicker-rails'  gem "select2-rails"    #images upload  gem "paperclip", "~> 4.2"  gem 'aws-sdk', '~> 1.6'    group :development do    gem 'capistrano', '~> 2'    gem 'spring'    gem 'better_errors'    gem 'binding_of_caller'    gem 'pry'    gem 'pry-rails'    gem 'awesome_print' # https://github.com/michaeldv/awesome_print  end    gem 'rails_12factor', group: [:production, :staging]    #user managment  gem 'devise'  gem 'cancancan', '~> 1.10'  gem 'recaptcha', require: 'recaptcha/rails'  #tracking user data  gem 'classy_enum'    #pagination  gem 'kaminari'    #api serialization  gem 'active_model_serializers'  # To use Jbuilder templates for JSON  gem 'jbuilder'    #dropbox  gem "dropbox-api"    #sidekiq jobs  gem 'sidekiq'  gem 'sidekiq-status'  gem 'sinatra', :require => nil    #for the folders hierarchy tree  gem 'closure_tree'    # PDFs  gem 'doc_raptor'    # Excel Parsing  gem 'roo'    # Emails  gem 'sendgrid'    # auto increment numbers  gem 'protokoll'    # State machine  gem 'aasm'    #elastic search  gem 'elasticsearch-model', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'  gem 'elasticsearch-rails', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'    gem 'rubyzip'    gem 'exception_notification', group: [:production, :staging], github: 'joshco/exception_notification'    gem 'spreadsheet'  


list of files in the app folder

drwxrwxr-x 11 ubuntu ubuntu 4096 Apr  1 08:03 app  drwxrwxr-x  2 ubuntu ubuntu 4096 Apr  1 08:03 bin  drwxrwxr-x  3 ubuntu ubuntu 4096 Apr  1 08:03 client  drwxrwxr-x  5 ubuntu ubuntu 4096 Apr  5 22:08 config  -rw-rw-r--  1 ubuntu ubuntu  153 Apr  1 08:03 config.ru  drwxrwxr-x  4 ubuntu ubuntu 4096 Apr  1 08:03 db  -rw-rw-r--  1 ubuntu ubuntu 1570 Apr  1 08:03 Gemfile  -rw-rw-r--  1 ubuntu ubuntu 9072 Apr  1 08:03 Gemfile.lock  drwxrwxr-x  5 ubuntu ubuntu 4096 Apr  1 08:03 gulp  -rw-rw-r--  1 ubuntu ubuntu  557 Apr  1 08:03 gulpfile.js  drwxrwxr-x  6 ubuntu ubuntu 4096 Apr  1 08:03 lib  drwxrwxr-x  2 ubuntu ubuntu 4096 Apr  6 13:48 log  -rw-rw-r--  1 ubuntu ubuntu 1393 Apr  1 08:03 package.json  -rw-rw-r--  1 ubuntu ubuntu  146 Apr  1 08:03 Procfile  -rw-rw-r--  1 ubuntu ubuntu  143 Apr  1 08:03 Procfile.example  drwxrwxr-x  2 ubuntu ubuntu 4096 Apr  1 08:03 public  -rw-rw-r--  1 ubuntu ubuntu  249 Apr  1 08:03 Rakefile  -rw-rw-r--  1 ubuntu ubuntu 7908 Apr  1 08:03 README.md  drwxrwxr-x  8 ubuntu ubuntu 4096 Apr  1 08:03 test  drwxrwxr-x  6 ubuntu ubuntu 4096 Apr  5 15:14 tmp  drwxrwxr-x  3 ubuntu ubuntu 4096 Apr  1 08:03 vendor  -rw-rw-r--  1 ubuntu ubuntu   64 Apr  1 08:03 webpack.config.js  

Why is Spree API tests complaining about missing templates for spree/api/shipments/show, spree/api/base/show

Posted: 07 Apr 2016 05:53 AM PDT

I'm making some tweaks to the Shipping API. To back this by test I've copied solidus/api/spec/controllers/spree/api/shipments_controller_spec.rb into MY_RAILS_APP/spec/controllers/spree/api

I've also copied the API views into my app.

cp -r solidus/api/app/views/spree/api/* app/views/spree/api/

So this is what's happening when I run the tests:

[93, 102] in /Users/martins/Work/Hoome/spec/controllers/spree/api/shipments_controller_spec.rb      93:      94:     it "can make a shipment ready", focus: true do      95:       allow_any_instance_of(Spree::Order).to receive_messages(paid?: true, complete?: true)      96:       api_put :ready      97:       debugger  =>  98:       expect(json_response).to have_attributes(attributes)      99:       expect(json_response["state"]).to eq("ready")     100:       expect(shipment.reload.state).to eq("ready")     101:     end     102:  (byebug)  (byebug) json_response  {"exception"=>"Missing template spree/api/shipments/show, spree/api/base/show   with {:locale=>[:en], :formats=>[:json], :variants=>[],   :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :rabl, :jbuilder], :versions=>[]}.   Searched in: \n  * \"/Users/martins/Work/Hoome/app/compiled_views\"\n  * \"/Users/martins/Work/Hoome/app/views\"\n  * \"/Users/martins/.rvm/gems/ruby-2.2.3@solidus/gems/solidus_auth_devise-1.3.0/lib/views/backend\"\n  * \"/Users/martins/.rvm/gems/ruby-2.2.3@solidus/gems/solidus_auth_devise-1.3.0/lib/views/frontend\"\n  * \"/Users/martins/.rvm/gems/ruby-2.2.3@solidus/gems/devise-3.5.6/app/views\"\n  * \"/Users/martins/Work/Hoome/solidus/frontend/app/views\"\n  * \"/Users/martins/Work/Hoome/solidus/backend/app/views\"\n  * \"/Users/martins/Work/Hoome/solidus/api/app/views\"\n  * \"/Users/martins/Work/Hoome/solidus/core/app/views\"\n  * \"/Users/martins/.rvm/gems/ruby-2.2.3@solidus/gems/kaminari-0.16.3/app/views\"\n"}  

/Users/martins/Work/Hoome/app/views/spree/api/shipments/show.v1.rabl is present, but I could not find any templates for spree/api/base/show. (If it is that the error message is complaining about).

Questions

  1. What should I do to get my test running?
  2. I would prefer not to copy views from the gem into my Rails app, if that is possible. Any ideas on how to do that?

variable in .click function not reset on second click

Posted: 07 Apr 2016 07:05 AM PDT

I've a jQuery function in rails which sets variable values from ajax and passes them to Pick A Date, every time an input is clicked.

The variables are only setting once in the javascript, and not every time an input is clicked.

PickADate's windows open correctly when any input is clicked -> but the values are just kept at the initial values for page load.

The variables correctly update in the #dates-array element's html, using ajax.

I notice if I drop an alert within that function, it also only fires once.

The site is using Turbolinks -> hence .on("page:change"

      $(document).on("click", ".pick-a-date input",function() {          var date_options;          var time_options;          date_options = $("#dates-array").data("pick-a-date-options");          time_options = $("#times-array").data("pick-a-time-options");          date_options = dateStringsToDateObjects(date_options);          time_options = dateStringsToDateObjects(time_options);          PICKERS.collection_date = $('#order_collection_time_date.datepicker')                                      .pickadate(date_options.collection_date_options)                                      .pickadate('picker');          PICKERS.collection_time = $('#order_collection_time_time.timepicker')                                      .pickatime(time_options.collection_time_options)                                      .pickatime('picker');          PICKERS.delivery_date = $('#order_delivery_time_date.datepicker')                                      .pickadate(date_options.delivery_date_options)                                      .pickadate('picker');          PICKERS.delivery_time = $('#order_delivery_time_time.timepicker')                                      .pickatime(time_options.delivery_time_options)                                      .pickatime('picker');          PICKERS.collection_date.on('close', collectionDateCallback);          PICKERS.collection_time.on('close', collectionTimeCallback);          PICKERS.delivery_date.on('close', deliveryDateCallback);          PICKERS.delivery_time.on('close', deliveryTimeCallback);          return;        });  

If anyone can see where I'm going wrong, it would be greatly appreciated.

UPDATE:

If I take out the two pick_a_date functions, the variables are set correctly. The problem only occurs when they are in the function.

PICKERS.collection_date =     $('#order_collection_time_date.datepicker')                              .pickadate(date_options.collection_date_options)                              .pickadate('picker');  PICKERS.delivery_date = $('#order_delivery_time_date.datepicker')                              .pickadate(date_options.delivery_date_options)                              .pickadate('picker');  

Adding User Input to a hash? Ruby

Posted: 07 Apr 2016 07:21 AM PDT

I am trying to create some simple programs as trying to learn Ruby and then move on to rails, I am just playing about to try and get used to the flow of how different types of code work variables, loops etc.

I am trying to create a simple book system were I already have 3 books in my hash and then I want to list the books already in the library in the console and then I want to be able to add new books and then also loop through and display the new list to the console.

require 'rubygems'    class GetDetailsFromUser    books = {        Eagle_Eye: 1,        Eage_Eye1: 2,        Eagle_Eye2: 3    }      books.each do |i|      puts i    end      while true      add = gets.chomp      break if add.empty?      books << add    end      puts 'New list is below'      books.each do |i|      puts i    end  end  

Were am I going wrong? I manage to print out the hash to the console, however, I get an error message

undefined method '<<' for {:Eagle_Eye=>1,...

Why is the method undefined? books << add? This should add a new book to the book hash table?

Results of infinte scroll are prepending instead of appending

Posted: 07 Apr 2016 05:01 AM PDT

I'm using the will_paginate gem to paginate a list of users on my user index page. This pagination is working properly, so that when I click for the users on page 2, I'm taken to those users.

However, I implemented 'infinite scroll' on another part of this site and it worked beautifully, so I wanted to do the same with the users index page. When I scroll down, I want the new users to appear at the bottom of the page 1 user table. Currently the issue I'm running into though is the users aren't being 'appended' at the end of the page 1 users, they're being 'pre-pended' above the page 1 users.

index.html.erb - users

<hr>  <div class="container">    <div class="row">      <div class="col-lg-12">        <div class="main-box no-header clearfix">          <div class="main-box-body clearfix">            <div class="table-responsive">              <table class="table user-list">                <thead>                  <tr>                    <th><span>User</span></th>                    <th><span>Friends</span></th>                    <th class="text-center"><span>Status</span></th>                  </tr>                </thead>                  <div id="all-users" >                    <%= render @users %>                  </div>                  <div id="infinite-scrolling">                    <%= will_paginate %>                  </div>              </table>            </div>          </div>        </div>      </div>    </div>  </div>  

_user.html.erb

<tbody>    <% unless user == current_user %>      <tr>        <td>          <%= image_tag user.gravatar_url default: "retro" %>          <%= link_to user.name, user_path(user) %>        </td>        <td><%= pluralize(user.friends.count, "Friend") %></td>        <td class="text-center">          <div id="friend-form">            <%= render partial: 'friendships/friendships_status', locals: {user: user} %>          </div>        </td>      </tr>    <% end %>  </tbody>  

Relevant CSS:

@import "bootstrap-sprockets";  @import "bootstrap";  @import "font-awesome";    .....    .user-list tbody td .user-subhead {      font-size: 0.875em;      font-style: italic;  }  .user-list tbody td .user-link {      display: block;      font-size: 1.25em;      padding-top: 3px;      margin-left: 60px;  }  a {      color: #3498db;      outline: none!important;  }  .user-list tbody td>img {      position: relative;      max-width: 50px;      float: left;      margin-right: 15px;  }    .table thead tr th {      text-transform: uppercase;      font-size: 0.875em;  }  .table thead tr th {      border-bottom: 2px solid #e7ebee;  }  .table tbody tr td:first-child {      font-size: 1.125em;      font-weight: 300;  }  .table tbody tr td {      font-size: 0.875em;      vertical-align: middle;      border-top: 1px solid #e7ebee;      padding: 12px 8px;  }  

In case it's helpful:

class UsersController < ApplicationController    def index      @users = User.all.paginate(page: params[:page], per_page: 15)    end  end  

I believe this issue relates to my CSS. When I look at the 'pre-pended' page 2 results, it appears they're not part of the table user-list class but are rather identified by their all-users id tag.

Rails validate model attribute based on value of another attribute

Posted: 07 Apr 2016 05:30 AM PDT

I have a rails app with User model which has state and city attributes.
I am using a gem to get the list of cities of a given state and country.
I want that while signing up if the city selected by user is not in the list of cities for the state selected by user then dont allow signup and show error.

    validates :state, presence: true, inclusion: { in: CS.states(:in).keys.collect{|x| x.to_s } }    validates :city, presence: true, inclusion: { in: CS.cities((:state).to_sym, :in) }  

I wrote this code in user.rb model but its not working.
:state should refer to the value submitted by user for 'state' attribute but i don't think that's working here. I want to pass the value of state given by user to the function CS.cities(). How do I fix this?

Nested attributes validations fails in parent association

Posted: 07 Apr 2016 05:18 AM PDT

If you want to go straight to the question, just go to the last paragraph.

A Pack has many items included, Item is polymorphic and one of the linked tables is Access (so Access is an Item that can be added to the Pack) Here you are the models and controller.

class Pack < ActiveRecord::Base    has_many :pack_items, dependent: :destroy    has_many :items_included, through: :pack_items, source: :item    accepts_nested_attributes_for :pack_items, allow_destroy: true      validate :valid_max_value, if: :infinite_item?  end    class Item < ActiveRecord::Base    has_many :pack_items, dependent: :restrict_with_error    has_many :packs, through: :pack_items  end    class Access < ActiveRecord::Base    has_one :item, as: :itemable, dependent: :destroy    has_one :entitlement, as: :entitlementable, dependent: :destroy    accepts_nested_attributes_for :item, allow_destroy: true    accepts_nested_attributes_for :entitlement, allow_destroy: true    validate :valid_max_value, if: :infinite?      private      def infinite?      entitlement.infinite    end  end    class PacksController < BaseController    def update      @pack = Pack.find(params[:id])      if @pack.update(permitted_params)         ...      end    end      private      def permitted_params      params.require(:pack).permit(item_attributes: [:id, :name, :max_purchasable],                                    pack_items_attributes: [:id, :item_id, :amount, :_destroy])    end  end  

There is an importan validation in pack "valid_max_value. If a pack has an infinite Access inside, the max_value of the Pack should never be higher than 1. It works perfectly when I create a pack and I add some Accesses, but the problem is this:

  • I have a Pack with two Items. An Access that's infinite and a common Access(not infinite). So the Pack's max_value should be 1 because it has an infinite Access inside.
  • Now I edit that Pack and I delete the infinite Access, so now I can select a higher max_value, 5 in example, because the pack doesn't have an Access with restriction inside.
  • When I click update there is a rollback because the valid_max_value validation runs before the deletion of the infinite Access, so it says the max_value is invalid because the validation depends on a child field.

In short, my question is: How can I delete the nested items before run the parent validation?

Rendering a file/template with layout outside of controller with Rails 4

Posted: 07 Apr 2016 05:38 AM PDT

Currently I am rendering a view in Rails 4 outside of a Controller with this code:

av = ActionView::Base.new(ActionController::Base.view_paths, {}, ActionController::Base.new)  av.config = Rails.application.config.action_controller  av.class_eval do    include ApplicationHelper  end    html = av.render(    file: '/users/index',    locals: {}  )  

How can I render the view inside of a layout? The following does not work:

html = av.render(    file: '/users/index',    locals: {}    layout: 'layouts/application'   )  

Thanks!

Running in "undefined method `to_sym' for nil:NilClass" when using activeadmin

Posted: 07 Apr 2016 05:32 AM PDT

I've installed activeadmin to my ruby-on-rails project. I can see every model except for one. When I click on the link for this model in the headbar I get an errorpage that says:

undefined method `to_sym' for nil:NilClass  Extracted source (around line #2):  insert_tag renderer_for(:index)  

The model that doesn't work is the only model with has-many-through relations. Here is the code of the model:

class Project < ActiveRecord::Base  belongs_to :person  belongs_to :regularity    has_many :groupings  has_many :groups, through: :groupings    has_many :localizations  has_many :locations, through: :localizations    has_many :categorizations  has_many :kategorien, through: :categorizations    has_many :agings  has_many :ages, through: :agings    accepts_nested_attributes_for :groupings  accepts_nested_attributes_for :localizations  accepts_nested_attributes_for :categorizations  accepts_nested_attributes_for :agings  accepts_nested_attributes_for :groups  accepts_nested_attributes_for :locations  accepts_nested_attributes_for :kategorien  accepts_nested_attributes_for :ages    def LinkToKategorie (arr)      arr.each do |kat|          Categorization.create(kategorie: kat, project: self)      end  end    def LinkToLocation (arr)      arr.each do |loc|          Localization.create(location: loc, project: self)      end  end    def LinkToGroup (arr)      arr.each do |gro|          Grouping.create(group: gro, project: self)      end  end    def LinkToAge (arr)      arr.each do |ag|          Aging.create(age: ag, project: self)      end  end  end  

Here is the full trace of the error:

activerecord (4.1.8) lib/active_record/reflection.rb:100:in `_reflect_on_association'  activerecord (4.1.8) lib/active_record/reflection.rb:537:in `source_reflection'  activerecord (4.1.8) lib/active_record/reflection.rb:575:in `chain'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/filters/resource_extension.rb:131:in `block in default_association_filters'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/filters/resource_extension.rb:131:in `reject!'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/filters/resource_extension.rb:131:in `default_association_filters'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/filters/resource_extension.rb:111:in `default_filters'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/filters/resource_extension.rb:96:in `filter_lookup'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/filters/resource_extension.rb:25:in `filters'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/filters/resource_extension.rb:154:in `block in filters_sidebar_section'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/helpers/optional_display.rb:25:in `instance_exec'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/helpers/optional_display.rb:25:in `display_on?'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/resource/sidebars.rb:17:in `block in sidebar_sections_for'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/resource/sidebars.rb:17:in `select'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/resource/sidebars.rb:17:in `sidebar_sections_for'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/views/pages/base.rb:112:in `sidebar_sections_for_action'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/views/pages/base.rb:136:in `skip_sidebar?'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/views/pages/base.rb:74:in `build_page_content'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/views/pages/base.rb:52:in `block (2 levels) in build_page'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:31:in `block in build_tag'  arbre (1.0.3) lib/arbre/context.rb:92:in `with_current_arbre_element'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:49:in `with_current_arbre_element'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:26:in `build_tag'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:39:in `insert_tag'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:14:in `div'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/views/pages/base.rb:48:in `block in build_page'  arbre (1.0.3) lib/arbre/context.rb:92:in `with_current_arbre_element'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:49:in `with_current_arbre_element'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/views/pages/base.rb:47:in `build_page'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/views/pages/base.rb:10:in `build'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:30:in `block in build_tag'  arbre (1.0.3) lib/arbre/context.rb:92:in `with_current_arbre_element'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:26:in `build_tag'  arbre (1.0.3) lib/arbre/element/builder_methods.rb:39:in `insert_tag'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/app/views/active_admin/resource/index.html.arb:2:in `block in __home_oscar__rbenv_versions_______lib_ruby_gems_______bundler_gems_activeadmin____b__e__d_f_app_views_active_admin_resource_index_html_arb___4298410947655854879_70101451315680'  arbre (1.0.3) lib/arbre/context.rb:45:in `instance_eval'  arbre (1.0.3) lib/arbre/context.rb:45:in `initialize'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/app/views/active_admin/resource/index.html.arb:1:in `new'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/app/views/active_admin/resource/index.html.arb:1:in `__home_oscar__rbenv_versions_______lib_ruby_gems_______bundler_gems_activeadmin____b__e__d_f_app_views_active_admin_resource_index_html_arb___4298410947655854879_70101451315680'  actionview (4.1.8) lib/action_view/template.rb:145:in `block in render'  activesupport (4.1.8) lib/active_support/notifications.rb:161:in `instrument'  actionview (4.1.8) lib/action_view/template.rb:339:in `instrument'  actionview (4.1.8) lib/action_view/template.rb:143:in `render'  actionview (4.1.8) lib/action_view/renderer/template_renderer.rb:55:in `block (2 levels) in render_template'  actionview (4.1.8) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'  activesupport (4.1.8) lib/active_support/notifications.rb:159:in `block in instrument'  activesupport (4.1.8) lib/active_support/notifications/instrumenter.rb:20:in `instrument'  activesupport (4.1.8) lib/active_support/notifications.rb:159:in `instrument'  actionview (4.1.8) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'  actionview (4.1.8) lib/action_view/renderer/template_renderer.rb:54:in `block in render_template'  actionview (4.1.8) lib/action_view/renderer/template_renderer.rb:62:in `render_with_layout'  actionview (4.1.8) lib/action_view/renderer/template_renderer.rb:53:in `render_template'  actionview (4.1.8) lib/action_view/renderer/template_renderer.rb:17:in `render'  actionview (4.1.8) lib/action_view/renderer/renderer.rb:42:in `render_template'  actionview (4.1.8) lib/action_view/renderer/renderer.rb:23:in `render'  actionview (4.1.8) lib/action_view/rendering.rb:99:in `_render_template'  actionpack (4.1.8) lib/action_controller/metal/streaming.rb:217:in `_render_template'  actionview (4.1.8) lib/action_view/rendering.rb:82:in `render_to_body'  actionpack (4.1.8) lib/action_controller/metal/rendering.rb:32:in `render_to_body'  actionpack (4.1.8) lib/action_controller/metal/renderers.rb:32:in `render_to_body'  actionpack (4.1.8) lib/abstract_controller/rendering.rb:25:in `render'  actionpack (4.1.8) lib/action_controller/metal/rendering.rb:16:in `render'  actionpack (4.1.8) lib/action_controller/metal/instrumentation.rb:41:in `block (2 levels) in render'  activesupport (4.1.8) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'  activesupport (4.1.8) lib/active_support/core_ext/benchmark.rb:12:in `ms'  actionpack (4.1.8) lib/action_controller/metal/instrumentation.rb:41:in `block in render'  actionpack (4.1.8) lib/action_controller/metal/instrumentation.rb:84:in `cleanup_view_runtime'  activerecord (4.1.8) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'  actionpack (4.1.8) lib/action_controller/metal/instrumentation.rb:40:in `render'  actionpack (4.1.8) lib/action_controller/metal/implicit_render.rb:10:in `default_render'  actionpack (4.1.8) lib/action_controller/metal/responder.rb:238:in `default_render'  actionpack (4.1.8) lib/action_controller/metal/responder.rb:165:in `to_html'  responders (1.1.2) lib/responders/flash_responder.rb:107:in `to_html'  actionpack (4.1.8) lib/action_controller/metal/responder.rb:158:in `respond'  actionpack (4.1.8) lib/action_controller/metal/responder.rb:151:in `call'  actionpack (4.1.8) lib/action_controller/metal/mime_responds.rb:400:in `respond_with'  inherited_resources (1.6.0) lib/inherited_resources/actions.rb:7:in `index'  /home/oscar/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/bundler/gems/activeadmin-988b34e77d1f/lib/active_admin/resource_controller/streaming.rb:12:in `index'  actionpack (4.1.8) lib/action_controller/metal/implicit_render.rb:4:in `send_action'  actionpack (4.1.8) lib/abstract_controller/base.rb:189:in `process_action'  actionpack (4.1.8) lib/action_controller/metal/rendering.rb:10:in `process_action'  actionpack (4.1.8) lib/abstract_controller/callbacks.rb:20:in `block in process_action'  activesupport (4.1.8) lib/active_support/callbacks.rb:113:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:113:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:229:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:229:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:229:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:229:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:166:in `block in halting'  activesupport (4.1.8) lib/active_support/callbacks.rb:86:in `call'  activesupport (4.1.8) lib/active_support/callbacks.rb:86:in `run_callbacks'  actionpack (4.1.8) lib/abstract_controller/callbacks.rb:19:in `process_action'  actionpack (4.1.8) lib/action_controller/metal/rescue.rb:29:in `process_action'  actionpack (4.1.8) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'  activesupport (4.1.8) lib/active_support/notifications.rb:159:in `block in instrument'  activesupport (4.1.8) lib/active_support/notifications/instrumenter.rb:20:in `instrument'  activesupport (4.1.8) lib/active_support/notifications.rb:159:in `instrument'  actionpack (4.1.8) lib/action_controller/metal/instrumentation.rb:30:in `process_action'  actionpack (4.1.8) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'  activerecord (4.1.8) lib/active_record/railties/controller_runtime.rb:18:in `process_action'  actionpack (4.1.8) lib/abstract_controller/base.rb:136:in `process'  actionview (4.1.8) lib/action_view/rendering.rb:30:in `process'  actionpack (4.1.8) lib/action_controller/metal.rb:196:in `dispatch'  actionpack (4.1.8) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'  actionpack (4.1.8) lib/action_controller/metal.rb:232:in `block in action'  actionpack (4.1.8) lib/action_dispatch/routing/route_set.rb:82:in `call'  actionpack (4.1.8) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'  actionpack (4.1.8) lib/action_dispatch/routing/route_set.rb:50:in `call'  actionpack (4.1.8) lib/action_dispatch/journey/router.rb:73:in `block in call'  actionpack (4.1.8) lib/action_dispatch/journey/router.rb:59:in `each'  actionpack (4.1.8) lib/action_dispatch/journey/router.rb:59:in `call'  actionpack (4.1.8) lib/action_dispatch/routing/route_set.rb:678:in `call'  warden (1.2.6) lib/warden/manager.rb:35:in `block in call'  warden (1.2.6) lib/warden/manager.rb:34:in `catch'  warden (1.2.6) lib/warden/manager.rb:34:in `call'  rack (1.5.5) lib/rack/etag.rb:23:in `call'  rack (1.5.5) lib/rack/conditionalget.rb:25:in `call'  rack (1.5.5) lib/rack/head.rb:11:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/params_parser.rb:27:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/flash.rb:254:in `call'  rack (1.5.5) lib/rack/session/abstract/id.rb:225:in `context'  rack (1.5.5) lib/rack/session/abstract/id.rb:220:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/cookies.rb:560:in `call'  activerecord (4.1.8) lib/active_record/query_cache.rb:36:in `call'  activerecord (4.1.8) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'  activerecord (4.1.8) lib/active_record/migration.rb:380:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'  activesupport (4.1.8) lib/active_support/callbacks.rb:82:in `run_callbacks'  actionpack (4.1.8) lib/action_dispatch/middleware/callbacks.rb:27:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/reloader.rb:73:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'  railties (4.1.8) lib/rails/rack/logger.rb:38:in `call_app'  railties (4.1.8) lib/rails/rack/logger.rb:20:in `block in call'  activesupport (4.1.8) lib/active_support/tagged_logging.rb:68:in `block in tagged'  activesupport (4.1.8) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (4.1.8) lib/active_support/tagged_logging.rb:68:in `tagged'  railties (4.1.8) lib/rails/rack/logger.rb:20:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/request_id.rb:21:in `call'  rack (1.5.5) lib/rack/methodoverride.rb:21:in `call'  rack (1.5.5) lib/rack/runtime.rb:17:in `call'  activesupport (4.1.8) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'  rack (1.5.5) lib/rack/lock.rb:17:in `call'  actionpack (4.1.8) lib/action_dispatch/middleware/static.rb:84:in `call'  rack (1.5.5) lib/rack/sendfile.rb:112:in `call'  railties (4.1.8) lib/rails/engine.rb:514:in `call'  railties (4.1.8) lib/rails/application.rb:144:in `call'  rack (1.5.5) lib/rack/content_length.rb:14:in `call'  puma (2.15.3) lib/puma/server.rb:541:in `handle_request'  puma (2.15.3) lib/puma/server.rb:388:in `process_client'  puma (2.15.3) lib/puma/server.rb:270:in `block in run'  puma (2.15.3) lib/puma/thread_pool.rb:106:in `call'  puma (2.15.3) lib/puma/thread_pool.rb:106:in `block in spawn_thread'  

The error occurs when I'm clicking on the Project link in the headbar of the dashboard of activeadmin. Every other link in the headbar shows the data of the model in al list view. Only this model doesn't work.

Hero with gradient using ::before not working correctly

Posted: 07 Apr 2016 05:30 AM PDT

I am trying to have a hero image page with a gradient using the ::before selector. The effect is working but there is one issue; it is out position so I want it to fit over the .hero div but there are some offset.

I only could get this working using the absolute position which is not the ideal for this.

.hero1 {    background: image-url('noche-en-santo-domingo.jpg') no-repeat fixed center;    background-size: cover;    height: 89vh;    &::before {      content: '';      position: absolute;      top: 6vw;      right: 0;      bottom: 0;      left: 0;      background-image: linear-gradient(to bottom right,#002f4b,#dc4225);      opacity: .4;     }      .intro {        padding: 3rem;        position: relative;        top: 50%;        transform: translateY(-50%);     }     }  

<section id="hero" class="hero1">     <div class="row intro">        <div class="small-centered medium-uncentered medium-6 large-7 columns">           <h1>We are caribbean developers</h1>           <p><strong>We Help the People make Better Software and we are young people with bilingual skills and professionalism, specializing in various areas of Information Technology (IT)</strong></p>        </div>        <div class="small-centered medium-uncentered medium-6 large-5 columns">           <div class="tech-img"></div>        </div>     </div>  </section>  

You can go and test here: http://carey.peopleware.do

Rails routes constraint - unicode regex not matching

Posted: 07 Apr 2016 04:42 AM PDT

So I have a route with a constraint that matches paths such as the following:

/jobs-in-London  get ':id' => 'search#show', :constraints => { :id => /jobs-in-[A-Z].*/ }  

This works great, but I need to match to locations written in other character sets, such as Japanese. I am happy for the "jobs-in-" to remain in english, since the valid urls are generated from a list of locations uploaded by the user.

This means I would be expecting to match /jobs-in-東京, which would then search in Tokyo once it hit the controller. Geolocation is done later, and works without translation. I just need to get the request to the right controller.

I have tried this:

get ':id' => 'search#show', :constraints => { :id => /jobs-in-\p{L}*/ }  

which I constructed using Rubular, and it appears to match correctly as seen here. I am aware this doesn't have the capital letter constraint, but that doesn't matter as some languages don't seem to have true capital letters anyway.

However the routes don't match it, and instead spit it out to the wildcard catch all at the bottom.

Am I falling foul of how Rails implements regex for routes? Does it not support the unicode selectors?

I cannot have this:

get ':id' => 'search#show', :constraints => { :id => /jobs-in-.*/ }  

as this matches /jobs-in-$£@ which is undesired, I want to constrain it to "letter" characters.

Find record which doesn't have any associated records with a specific value

Posted: 07 Apr 2016 05:49 AM PDT

I have a couple of models: User and UserTags

A User has_many UserTags  A UserTag belongs_to User  

I am trying to find all the Users which don't have a UserTag with name 'recorded' (so I also want users which don't have any tags at all). Given a users relation, I have this:

users.joins("LEFT OUTER JOIN user_tags ON user_tags.user_id = users.id AND user_tags.name = 'recorded'").  where(user_tags: { id: nil })  

Is there any other better or more Railsy way of doing this?

Enable LeadHistory/ Lead field tracking via salesforce api

Posted: 07 Apr 2016 04:25 AM PDT

I am using restforce gem for salesforce apis. I am able to do operations i wanted to be performed with it. I want to fetch the lead changes which I can get via

client.query('select Id from LeadHistory')

But couldn't find the way to enable the lead history tracking by api.

Testing Views in Rspec , undefined method collect

Posted: 07 Apr 2016 05:33 AM PDT

I got this following error while i am testing views in Rspec.

1) problems/new renders new problem form

Failure/Error:   <div class="col-md-8 col-sm-8">    <%= f.select :approval_status, options_for_select(@approval_statuses.collect { |as| [as[0].humanize, as[0]] }, selected: @problem.approval_status), {}, class: "form-control" %>  </div>  ActionView::Template::Error:    undefined method `collect' for nil:NilClass  

I am passing @approval_statuses in controller action. It's working fine in views , but in test cases i am getting this error.

Controller Action :

def new     @problem = Problem.new     @approval_statuses = Problem.approval_statuses     @visibilities = Problem.visibilities  end  

In Model

enum approval_status: {not_approved: 0, approved: 1}  

In new.html.erb_spec.rb

require 'rails_helper'    RSpec.describe "problems/new", type: :view do    before(:each) do    assign(:problem, Problem.new())    end      it "renders new problem form" do     render     assert_select "form[action=?][method=?]", problems_path, "post" do     end      end  end  

Cocoon fields rendering wrong ID in deep nesting

Posted: 07 Apr 2016 04:24 AM PDT

I have a rather complicated form that I'm putting together with cocoon and am having trouble getting the correct id for some of my fields to properly reflect the nesting. In summary, I have three different instances of nested fields via cocoon in one deeply nested partial. One of those fields renders the id perfectly fine (all nested models included). The other two leave out the highest level model from the id.

The models are as follows:

You need only be concerned with four: Stock, Stockholder, EntityJoin, Person and Org.

Stock has_many :stockholders

class Stockholder < ActiveRecord::Base      belongs_to :stock      belongs_to :entity, polymorphic: true      has_many :entity_joins, as: :holder      accepts_nested_attributes_for :entity_joins, allow_destroy: true        has_many :people,    through: :entity_joins, source: :entity, source_type: 'Person'      accepts_nested_attributes_for :people, allow_destroy: true      has_many :orgs, through: :entity_joins, source: :entity, source_type: 'Org'      accepts_nested_attributes_for :orgs, allow_destroy: true  

I have a form for Stock, which allows me to dynamically create Stockholders. For each stockholder, a user can either manually add an EntityJoin (which joins an existing Person or Org to the Stockholder) or the user can create a new Person or Org.

So nested within Stockholder (which itself is nested in a simple_form_for Stock), I have the following partial:

<div class="holder_fields holderStop">      <div class="holderTextEntry">          <span>              <input class="typeahead">              <span class="newEntityButtons">                  <span class="prefix">New</span>                  <span class="addpersonbutton newHolder newPerson">Person</span>                  <span class="addorgbutton newHolder newOrg">Company</span>              </span>          </span>      </div>      <div class="entityBoxes">        </div>      <div class="entitiesTechincal">          <label>From Existing Contacts</label>          <div class="existing_contacts new_fields">              <%= f.simple_fields_for :entity_joins do |ejoin| %>                  <%= render 'shared_equity/entity_join_fields', f:ejoin %>              <% end %>          </div>          <div>              <%= link_to_add_association 'Add Existing Contact', f, :entity_joins, partial: 'shared_equity/entity_join_fields', :"data-association-insertion-node" => "div.existing_contacts", :"data-association-insertion-method" => "append", class: "btn btn-default add-button" %>          </div>          <label>From Existing Contacts</label>          <div class="new_person new_fields">              <div>                  <%= link_to_add_association "Create New Person", f, :people, partial: 'shared_equity/person_fields', class: "btn btn-default add-button" %>              </div>          </div>          <label>From Existing Contacts</label>          <div class="new_fields new_org">              <div>                  <%= link_to_add_association "Create New Company", f, :orgs, partial: 'shared_equity/org_fields', class: "btn btn-default add-button" %>              </div>          </div>      </div>  </div>  

The partial contains three applications of cocoon as described above. You may notice that I only have simple_fields for :entity_joins and not for the other two. This is done intentionally as it suits my specific application.

The problem:

While my entity_joins fields render just fine, with an id of stock_stockholders_attributes_0_entity_joins_attributes_0_..., my :people and :orgs fields only render with an id of stockholder_people_attributes_.... (The key concern being the lack of any reference to stock_ at the beginning.) As you can imagine, this causes major trouble while saving it, as the nesting is off.

What might be causing this? Many thanks in advance for any help. I realize this is somewhat complicated.

No comments:

Post a Comment