Thursday, October 6, 2016

Rails 5 - ENV DATABASE_URL - specify encoding and collation | Fixed issues

Rails 5 - ENV DATABASE_URL - specify encoding and collation | Fixed issues


Rails 5 - ENV DATABASE_URL - specify encoding and collation

Posted: 06 Oct 2016 08:00 AM PDT

Our database.yml is added to .gitignore so devs can customize local environments and we plan to use ENV['DATABASE_URL'] for production servers. For default setup, this works. However, we need to configure encoding and collation to utf8mb4.

  • encoding: utf8mb4
  • collation: utf8mb4_unicode_ci

I tried padding it to query parameters, like the ?pool=5 example in the docs, but it doesn't seem to work.

DATABASE_URL=mysql2://user:passwd@host:port/dbname?encoding=utf8mb4&collation=utf8mb4_unicode_ci  

The tables created are still using the default encoding/collation so I assume the parameters doesn't work. Is there any way I could configure this by any other methods? Encoding and collation is the same for all environments.

Requirement is that dev environment can have a file with a config whereas prod should have no special file added, it should only use ENV variables. Maybe add this to one of the files inside config dir like application.rb or other files?

Thanks in advance.

PS: I'm new to Rails and Ruby (1 week) since I'm coming from PHP/Python.

Rails.application.secrets.KEY_NAME returns Uninitiated Constant (NameError)

Posted: 06 Oct 2016 07:56 AM PDT

I am trying to access an API and cannot get the key in secrets.yml to authorize.

I have gone into rails console and confirmed that Rails.application.secrets.KEY_NAME returns the correct key. But it isn't working when I run the .rb file.

How can I get it to work the way it's supposed to?

Add class to image_tag in Rails with IF statement

Posted: 06 Oct 2016 07:52 AM PDT

I have a image tag setup for a blog that if an image has been attached to the blog then display the image.

<%= image_tag blog.image_url(:thumb) if blog.image? %>  

I am trying to add a class to this image tag so that I can use CSS to edit it. I have tried a few different ways to add the class but none seem to work.

<%= image_tag blog.image_url(:thumb) if blog.image?, :class => "img" %>  

or

<%= image_tag (blog.image_url(:thumb), :class => "img") if blog.image? %>  

or

<%= image_tag (blog.image_url(:thumb) if blog.image?), :class => "img" %>  

does anyone know how to add a class to this type of statement?

Rails Cart deleting itself

Posted: 06 Oct 2016 07:44 AM PDT

I'm having an issue with my cart in an e-commerce app. When the user signs in and adds an item to Cart, the item does not add immediately. The user has to go back and add it a second time before it goes into the cart.

I've looked at the logs and i've been able to find that the issue occurs when a user has previously purchased something and is signing to purchase at a later time.The next time they log in to purchase another item, is when it occurs.

The system tries to delete the old cart and create a new one but what ultimately happens is, the new cart shows up empty on first attempt.

Is there a way to avoid this?

Any help would be appreciated. Thanks in advance!

def show if current_user if current_user.cart.purchased_at session[:cart_id] = nil else @cart = current_user.cart ||= Cart.find_by(session[:cart_id]) end end if session[:cart_id].nil? current_user.cart = Cart.create!(user_id: params[:id]) session[:cart_id] = current_user.cart.id end @cart = current_user.cart end

Most recent record form Elasticsearch Rails based on Multiple indices

Posted: 06 Oct 2016 07:48 AM PDT

I have two models in my Rails application: Share and Rent.

I'm starting to use ElasticSearch in my application and wanted a way to bring the models rent and share most recent.

I tried the following:

@response = Elasticsearch::Model.search query:     {    "indices": {      "indices": [        "shares",        "rents"      ],      "query": {        "multi_match": {          "query": "Apartament",          "fields": [ "tipe"]        }      },      "no_match_query": {        "term": {          "": ""        }      },      }  }  

But I do not know how to bring the most recent based on create_at field.

batch jpg images in string not all written to file with ruby file open write barby gem

Posted: 06 Oct 2016 07:41 AM PDT

I am using barby gem to generate barcodes. I am doing it a batch at a time and then save all of them in a file to be viewed by the user. I am not trying to print one at a time.

  def generate_barcode      number_of_instances = params[:times].to_i      value = 12.times.map{rand(10)}.join        barcodes = 10.times.collect { Barby::EAN13.new(value) } #collects ten barcodes in an array      processed_barcodes = barcodes.map {|barcode| barcode.to_jpg_2(:height => 60)} #returns an array and each element is a string of jpeg file      File.open('code.jpg', 'wb') do |f|         processed_barcodes.each {|barcode| f.write(barcode)} #stuck here        #f.puts(processed_barcodes) #tried this      end        send_file('code.jpg',        :type        => 'image/jpeg',        :disposition => 'inline'      )      end  

the view

<%= image_tag(url_for({:controller => 'business_partners', :action => 'generate_barcode', :format => 'jpg' })) %>  

processed_barcodes.count came back with 10.

My code.jpg got processed but I only have 1 image.

How to assign two foreign keys to the same parent table with rails migration? [duplicate]

Posted: 06 Oct 2016 07:33 AM PDT

I have User model and trying to create Contact model with foreign keys having such code in migration:

def change    create_table :contacts do |t|      ...      t.reference :user, index:true, foreign_key: { column_name: :created_by }      t.reference :user, index:true, foreign_key: { column_name: assigned_to }  

But there is only one column created in schema.rb:

t.integer "user_id  

Questions:

  1. What's wrong with my code?
  2. Do I really need to assign foreign key in migration through t.references? Can I simply create t.integer fields with right names and indexes and set foreign_key option in contact.rb?

Rails - How to ensure a parameter is updated correctly

Posted: 06 Oct 2016 07:48 AM PDT

I'm building an events app using rails. For the payment process I'm using Stripe and some javascript to update the amounts. I want the user to be able to specify the number of spaces (quantity) they wish to pay for and for this to update the total amount they then need to pay. The code I'm using is updating the text for the total amount payable but it's not updating the server so every time I do a test payment only one single amount is collected. So, if an event costs £10 per space and I try and input, say, 4 spaces (£40) when I do a test only £10 has been collected by Stripe. I need to ensure the quantity parameter is being passed correctly.

This is my booking page code -

new.booking.html.erb

    <div class="col-md-6 col-md-offset-3" id="eventshow">    <div class="row">      <div class="panel panel-default">          <div class="panel-heading">              <h2>Confirm Your Booking</h2>          </div>                        <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %>                     <div class="calculate-total">                                <p>                                    Confirm number of spaces you wish to book here:                                      <input type="number" placeholder="1"  min="1" value="1" class="num-spaces">                                </p>                                  <p>                                      Total Amount                                      £<span class="total" data-unit-cost="<%= @event.price %>">0</span>                                  </p>                            </div>                         <span class="payment-errors"></span>                    <div class="form-row">                      <label>                        <span>Card Number</span>                        <input type="text" size="20" data-stripe="number"/>                      </label>                  </div>                    <div class="form-row">                    <label>                    <span>CVC</span>                    <input type="text" size="4" data-stripe="cvc"/>                    </label>                  </div>                    <div class="form-row">                      <label>                          <span>Expiration (MM/YYYY)</span>                          <input type="text" size="2" data-stripe="exp-month"/>                      </label>                      <span> / </span>                      <input type="text" size="4" data-stripe="exp-year"/>                  </div>              </div>              <div class="panel-footer">                       <%= form.button :submit %>                  </div>     <% end %>  <% end %>          </div>    </div>  </div>      <script type="text/javascript">      $('.calculate-total input').on('keyup change', calculateBookingPrice);    function calculateBookingPrice() {    var unitCost = parseFloat($('.calculate-total .total').data('unit-cost')),        numSpaces = parseInt($('.calculate-total .num-spaces').val()),        total = (numSpaces * unitCost).toFixed(2);      if (isNaN(total)) {      total = 0;    }      $('.calculate-total span.total').text(total);      }      $(document).ready(calculateBookingPrice)    </script>  

This is my controller code with the quantity param -

bookings_controller.rb

    def new      # booking form      # I need to find the event that we're making a booking on      @event = Event.find(params[:event_id])      # and because the event "has_many :bookings"      @booking = @event.bookings.new(quantity: params[:quantity])      # which person is booking the event?      @booking.user = current_user      #@total_amount = @event.price * @booking.quantity      end    def create        # actually process the booking      @event = Event.find(params[:event_id])      @booking = @event.bookings.new(booking_params)      @booking.user = current_user            if               @booking.reserve              flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          else              flash[:error] = "Booking unsuccessful"              render "new"          end  end  

How do I amend this so the total amount is correctly collected?

OpenSSL::PKey::RSAError (Neither PUB key nor PRIV key: nested asn1 error) while using Grocer gem on RoR app

Posted: 06 Oct 2016 07:23 AM PDT

I know there are a lot of questions on this scenario but I've tried every solution and I am still stuck. I am using the grocer gem to send push notifications to the APN service. I am stuck on the certificate issue.

Here's the code

pusher = Grocer.pusher(    certificate: "#{Rails.root}/public/certificate1.pem",      # required    passphrase:  "",                       # optional    gateway:     "gateway.push.apple.com", # optional; See note below.    port:        2195,                     # optional    retries:     3                         # optional  )       notification = Grocer::Notification.new(    device_token: token,    alert: "#{uname} liked your post",    sound: 'default',    badge:  0  )    pusher.push(notification)  

I am in a production environment where I am hosting the app on Heroku. Heroku logs show me this

OpenSSL::PKey::RSAError (Neither PUB key nor PRIV key: nested asn1 error):  app/controllers/api/v1/feeds_controller.rb:49:in `likeit'  

Line 49 is the line where the notification is pushed.

I'm certain that the certificate I'm using is proper as I have tested push notifications using it. Also when generating the pem file I have exported both the certificate as well as the private key.

Reference: grocer gem

Any suggestions are welcome!

undefined method 'to_model' when linking thumbnail to original image

Posted: 06 Oct 2016 07:25 AM PDT

I'm creating an album that I'm planning to display with Masonry and ImgZoom so that the visitors can have a bigger image when they click on it.

According to ImgZoom, to make the zoom work, you need to do the following:

<a href="path/to/real/image.png">      <img src="path/to/image's/thumbnail.png class="thumbnail" />  </a>  

So I generated an uploader, with the following inside it:

class ImageUploader < CarrierWave::Uploader::Base      include CarrierWave::MiniMagick      storage :file      def store_dir      'portfolio/photos'    end      version :thumb do      process :resize_to_fit => [220, nil]    end  end  

Everything works perfectly, I can call both the versions without trouble, but when I try to follow ImgZoom's instructions by doing the following:

<%= @portfolio.photos.each do |p| %>   #This is a nested form inside the portfolio form, so I need to do this to get my images    <%= link_to image_tag p.image.thumb.url, p.image %>  

or:

<%= link_to p.image do %>      <%= image_tag p.image.thumb.url, :class => 'thumbnail' %>  <% end %>  

I'm getting the following error: undefined method 'to_model' for #<ImageUploader:0x0000000c35f4d8>

I found a similar subject on stack overflow but the asker wasn't clear and was invited to ask an other question on the forum, which I couldn't find. I can individually reach 'p.image' and 'p.image.thumb.url', but I can't make a link from one to another, which would be perfectly doable with simple html.

What am I doing wrong?

Thank you in advance

How to check remove image? I can not check because before save averter.present? return true

Posted: 06 Oct 2016 07:37 AM PDT

I use carrierwaveuploader/carrierwave: Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks.

@foo.assign_attributes(update_params) #=> update_params includes "remove_avatar"=>"1"  @foo.avatar.present? #=> true  @foo.save  @foo.avatar.present? #=> false  

before save present? return true. after save present? return false.

My Validation

validate :validate_avatar    def validate_avatar    # if @foo.avatar deleted and same conditions, add error  end  

In validate_avatar, @foo.avatar.present? is true because before save.

I try after_save :validate_avatar.

after_save :validate_avatar    def validate_avatar    # if @foo.avatar deleted and same conditions, add error    # then return false  end  

Because after_save, @foo.avatar.present? is false. But Rails5 not rollback with return false.

How to check @foo.avatar deleted in validation?

I want to check avatar was deleted but remain image crop data. So I need check @foo.avater deleted or not delete. If avatar deleted, image crop data deleted too. So check in validation.

Already made a method for delete all image crop data(xxx_crop columns) in my project.

Issue installing ruby 2.3.1 with rvm on Linux Mint Rafaela

Posted: 06 Oct 2016 07:03 AM PDT

I'm trying to install ruby 2.3.1 with rvm, but it keeps throwing me this error, never happened to me before:

Searching for binary rubies, this might take some time.  No binary rubies available for: mint/17.2/x86_64/ruby-2.3.1.  Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.  Checking requirements for mint.  Requirements installation successful.  Installing Ruby from source to: /usr/share/rvm/rubies/ruby-2.3.1, this may take a while depending on your cpu(s)...  ruby-2.3.1 - #downloading ruby-2.3.1, this may take a while depending on your connection...  ruby-2.3.1 - #extracting ruby-2.3.1 to /usr/share/rvm/src/ruby-2.3.1....  ruby-2.3.1 -    #configuring..........................................................  ruby-2.3.1 - #post-configuration..  ruby-2.3.1 - #compiling............................................................................................................  Error running '__rvm_make -j2',  showing last 15 lines of /home/kristian/.rvm/log/1475760763_ruby-2.3.1/make.log   Get_EC_KEY((obj), (key)); \   ^   ossl_pkey_ec.c:699:5: note: in expansion of macro 'Require_EC_KEY'   Require_EC_KEY(self, ec);   ^   make[2]: *** [ossl_pkey_ec.o] Error 1   make[2]: Leaving directory `/usr/share/rvm/src/ruby-2.3.1/ext/openssl'   make[1]: *** [ext/openssl/all] Error 2   make[1]: *** Waiting for unfinished jobs....   installing default pathname libraries   linking shared-object pathname.so   make[2]: Leaving directory `/usr/share/rvm/src/ruby-2.3.1/ext/pathname'   make[1]: Leaving directory `/usr/share/rvm/src/ruby-2.3.1'   make: *** [build-ext] Error 2   ++ return 2   There has been an error while running make. Halting the installation.  

I mean, seems like it's not finding a candidate for Linux Mint, but still, it looks like it's installing,so I don't get it.

Any ideas about this?

Could it be ssl related?

Thanks in advance!

rspec error michael hartl lesson 3

Posted: 06 Oct 2016 07:02 AM PDT

while executing the command

$ bundle exec rspec spec/requests/static_pages_spec.rb

i get this error /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in require': cannot load such file -- test/unit/assertions (LoadError) from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:inblock in require' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:214:in load_dependency' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:inrequire' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-rails-2.13.1/lib/rspec/rails/adapters.rb:3:in <top (required)>' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:inrequire' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in block in require' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:214:inload_dependency' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in require' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-rails-2.13.1/lib/rspec/rails.rb:11:in' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in require' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:inblock in require' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:214:in load_dependency' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:inrequire' from /home/sarfraz/Desktop/Rails Apps/sample_app/spec/spec_helper.rb:4:in <top (required)>' from /home/sarfraz/Desktop/Rails Apps/sample_app/spec/requests/static_pages_spec.rb:1:inrequire' from /home/sarfraz/Desktop/Rails Apps/sample_app/spec/requests/static_pages_spec.rb:1:in <top (required)>' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:inload' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in block in load_spec_files' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:ineach' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in load_spec_files' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:22:inrun' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in run' from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:inblock in autorun'

this is my gemfile: source 'https://rubygems.org'

Bundle edge Rails instead: gem 'rails', github: 'rails/rails'

gem 'rails', '4.0.8'

Use sqlite3 as the database for Active Record

group :development, :test do gem 'sqlite3' gem 'rspec-rails', '2.13.1' end

group :test do gem 'selenium-webdriver', '2.35.1' gem 'capybara', '2.1.0' end

Use SCSS for stylesheets

gem 'sass-rails', '~> 4.0.2'

Use Uglifier as compressor for JavaScript assets

gem 'uglifier', '>= 1.3.0'

Use CoffeeScript for .js.coffee assets and views

gem 'coffee-rails', '~> 4.0.0'

gem 'therubyracer', platforms: :ruby

Use jquery as the JavaScript library

gem 'jquery-rails'

gem 'turbolinks'

gem 'jbuilder', '~> 1.2'

group :doc do # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', require: false end

group :production do gem 'pg', '0.15.1' gem 'rails_12factor', '0.0.2' end

Use ActiveModel has_secure_password

gem 'bcrypt', '~> 3.1.7'

Use unicorn as the app server

gem 'unicorn'

Use Capistrano for deployment

gem 'capistrano', group: :development

Use debugger

gem 'debugger', group: [:development, :test]

please help i cannot proceed totally stuck.. Thanks in advance

Using ruby on rails on windows [on hold]

Posted: 06 Oct 2016 07:00 AM PDT

Goood day people, please im trying to use ruby on rails on windows with great difficulty, i already installed the ruby, installed rails, installed sqlLite. I already created an application using "rails new app". i tried the run bundle command but it just spewed out a bunch of tips. Can you help on how to use ruby on rails on windows

social-share-button gem not working when a social site icon is clicked

Posted: 06 Oct 2016 06:54 AM PDT

I am using social-share-button gem to share stories in social networks like facebook, twitter, etc. Whenever a social site button is clicked, it is just going to the top of the page instead of showing a pop-up or new tab to share. I have used https://github.com/huacnlee/social-share-button.

Can anyone suggest where I have gone wrong?

Algolia_search on nested model

Posted: 06 Oct 2016 06:28 AM PDT

I got a User model, which has many Skills though his Masteries.

I'm using a form to retrieve users, with Algoliasearch, and I would like to retrieve all users that have a particular skill (I.E, if I got a user called "John", which has the "Origami" skill, he should appear in results if I type "John" or "Origami")

I tried to do so by mapping the nested skills, but this doesn't seem to work

Here's the model

class Creator < ActiveRecord::Base  include AlgoliaSearch      algoliasearch do    # all attributes will be sent    add_attribute :creator_skills  end    has_many :masteries  has_many :skills, through: :masteries    def creator_skills    self.masteries.map do |s|      { name: s.skill.name }    end  end    [...]  

The form returns a query param, which is used to retrieve creators with

  @creators = Creator.where(display_index: true).algolia_search(params[:query]).shuffle  

Did I miss something ? Is it possible to map a nested model ?

Ruby gem cucumber SSL error and Gem sources

Posted: 06 Oct 2016 07:58 AM PDT

I was trying to install cucumber gem for Ruby. Although there were few topics somewhat related to this, I can't find exact question with exact answer. When on Windows I try to run the command gem install cucumber and the console returned:

ERROR: Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://s3.amazonaws.com/production.s3.rubygems.org/specs.4.8.gz)

Then, I googled for a solution and found some suggestions to remove source in here. I ran gem sources -r and it has been removed.

But did that not only in cucumber. Now I'm even unable to add source.

how to create a model corresponding a view in rails

Posted: 06 Oct 2016 06:56 AM PDT

I created a view "Employee_Details" in mysql, which is combination of 7 tables like "user", "user_details", "location", "offer_letters", "employee_details", "client" etc. It showing all details of a user. I am accessing all values with the help of hr_controller.rb with sqlconnection.rb file. sqlconnection.rb file create in model folder and it's contain all sql connection. But I want to create a model for Employee_Details. Can i access all information of Employee_Details view, with the help of new model After that I will export all information into excel file

Deprecation warnings in Rails 5

Posted: 06 Oct 2016 07:13 AM PDT

Every time I execute my tests, I get these deprecation warnings:

DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super. (called from <top (required)> at /Users/johnvanarkelen/Documents/Web development/rails/test-eagle/config/environment.rb:5)  DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super. (called from <top (required)> at /Users/johnvanarkelen/Documents/Web development/rails/test-eagle/config/environment.rb:5)  DEPRECATION WARNING: after_filter is deprecated and will be removed in Rails 5.1. Use after_action instead. (called from <top (required)> at /Users/johnvanarkelen/Documents/Web development/rails/test-eagle/config/environment.rb:5)  

When I check line 5 of config/environment.rb, there is this code:

Rails.application.initialize!  

When I search my repo for after_action, after_filter or alias_method_chain, it is not found. What can I do to get rid of these warnings?

Rails test keeps crashing

Posted: 06 Oct 2016 06:10 AM PDT

Everytime I run rails test I get this error followed by thousand lines of text:

Running via Spring preloader in process 51653 /Users/Joseph/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/sqlite3_adapter.rb:27: [BUG] Segmentation fault at 0x00000000000110 ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

Sometimes when I run bin/spring stop it fixes the problem temporarily, but then it randomly comes back again.

Any help please?

search records by user in the scope

Posted: 06 Oct 2016 06:12 AM PDT

I need to search all the records where IdEmpresa: current_usuario.empresa_id the scope is this:

scope :por_empresa, -> { where(IdEmpresa: current_usuario.empresa_id) }  

But I get this error:

undefined local variable or method current_usuario' for Vendedor(Table doesn't exist):Class Did you mean? current_scope

Can I not call the current_user in the model?

./phantomjs: error while loading shared libraries: libssl.so.1.0.0 in AWS

Posted: 06 Oct 2016 06:18 AM PDT

I am having phantomjs 2.0.0 for screen capturescenario in my Rails application. It is working fine in production mode but when I moved the code to AWS, it is showing error as: (For example I am trying to check the version)

[root@ip-xxx-xx-xx-xxxbin]# ./phantomjs --version ./phantomjs: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory

Please help.

how to display each object in array in rails form_for

Posted: 06 Oct 2016 06:07 AM PDT

<%=form_for @question do |f|%>      <%=f.label :name, "Question:"%>    <%=f.text_field :name%>      <%=f.label :answer, "Answer:"%>    <%=f.text_field :answer%>      <%=f.label :wrong_answers%>    <%=f.text_field :wrong_answers, multiple: true%>      <%=f.label :wrong_answers%>    <%=f.text_field :wrong_answers, multiple: true%>      <%=f.label :wrong_answers%>    <%=f.text_field :wrong_answers, multiple: true%>  <%end%>  

when I create a question like this,

Question.create(    name: "1+1?",    answer: "2",    wrong_answers: ["1", "4", "3"])  

The edit form displays every wrong_answer text fields as ["1", "4", "3"]. My question is how do I get it to display each number on different text fields.

Rails active admin undefined methods

Posted: 06 Oct 2016 06:40 AM PDT

I'm using this code:

ActiveAdmin.register_page "Dashboard" do        section "Recent Posts" do           table_for Post.order("id desc").limit(15) do              column :id              column "Post title", :title do |post|                     link_to post.title,[:admin,post]              end              column :category,sortable: :category              column :created_at          end          strong (link_to "Show all posts")      end  end  

and I get this error:

undefined method `section'  

if I delete 'section' do-end part, then I get error for:

undefined method `table_for'  

and so on...

Seems like I cant use any of active admin given methods, maybe I'm mising something? Any gems or something? I installed active admin gem using this setup:

gem 'inherited_resources', github: 'activeadmin/inherited_resources'  gem 'activeadmin', github: 'activeadmin'  gem 'devise', github: 'plataformatec/devise'  

I'm using rails 5

.where returns nil exception if user does not enter anything rails 4

Posted: 06 Oct 2016 05:38 AM PDT

I want to query some data from table based on user for submission.

Its working fine but if I post nothing in the the fields and post my form, it returns me nil exception.

Is there a way we can deal with nil exception, or do I need to change query?

question_options = question.question_options.where(id: self.option_id).first  

Rails like query return records if posted empty

Posted: 06 Oct 2016 05:30 AM PDT

I am having an issue, if I post an empty text field for searching records using like query it started to show records:

Code is:

question_options = question.question_options.where("quiz_id = ? AND   lower(option) like ?", self.quiz_id, "%#{self.answer_text.downcase}%").first  

Output:

SELECT  "question_options".* FROM "question_options" WHERE   "question_options"."question_id" = $1 AND (quiz_id = 2 AND lower(option) like   '%%')  ORDER BY created_at asc LIMIT 1  

Notify.js with rails

Posted: 06 Oct 2016 07:40 AM PDT

I have a simple notification template. I just want to apply a notification alert in my page. Not for button click, I need to show it after sign in / sign out events like that. I found a library which is very simple. Here is the link

I used it's styles and load it. It display correctly but jquery functions are not working. Here is my code for template

<% if !flash.nil? %>      <div class="alert-wrapper">        <% flash.each do |name, msg| %>          <div id="notifications" class="alert alert-success alert-<%= name %>" role="alert"><%= msg %></div>        <% end %>      </div>  <% end %>  

JS file

    $( document ).ready(function() {    Notify = function(text, callback, close_callback, style) {    var time = '10000';  var $container = $('#notifications');  var icon = '<i class="fa fa-info-circle "></i>';    if (typeof style == 'undefined' ) style = 'warning'    var html = $('<div class="alert alert-' + style + '  hide">' + icon +  " " + text + '</div>');    $('<a>',{    text: '×',    class: 'button close',    style: 'padding-left: 10px;',    href: '#',    click: function(e){      e.preventDefault()      close_callback && close_callback()      remove_notice()    }  }).prependTo(html)    $container.prepend(html)  html.removeClass('hide').hide().fadeIn('slow')    function remove_notice() {    html.stop().fadeOut('slow').remove()  }    var timer =  setInterval(remove_notice, time);    $(html).hover(function(){    clearInterval(timer);  }, function(){    timer = setInterval(remove_notice, time);  });    html.on('click', function () {    clearInterval(timer)    callback && callback()    remove_notice()  });      }  });  

What am I missing here?

How to keep array structure when saving record - activerecord/postgres

Posted: 06 Oct 2016 06:57 AM PDT

I created an array structure of hashes and i created a column in postgres to save that structure using the migration below

class AddKeyDirectionsToEvent < ActiveRecord::Migration[5.0]    def change      add_column :calendar_events, :key_directions, :text, array:true, default: []    end  end  

now, the structure of the array is the one below

{      :in => [          [0] {                 :duration => "5 mins",                 :distance => "0.4 km",              :travel_mode => "WALKING",              :travel_type => nil          },          [1] {                 :duration => "12 mins",                 :distance => "5.3 km",              :travel_mode => "TRANSIT",              :travel_type => "SUBWAY"          },          [2] {                 :duration => "9 mins",                 :distance => "0.7 km",              :travel_mode => "WALKING",              :travel_type => nil          }      ]  }  {      :out => [          [0] {                 :duration => "10 mins",                 :distance => "0.7 km",              :travel_mode => "WALKING",              :travel_type => nil          },          [1] {                 :duration => "12 mins",                 :distance => "5.3 km",              :travel_mode => "TRANSIT",              :travel_type => "SUBWAY"          },          [2] {                 :duration => "6 mins",                 :distance => "0.4 km",              :travel_mode => "WALKING",              :travel_type => nil          }      ]  }  

but for some reason in database it is saved like this

["{:in=>[{:duration=>\"5 mins\", :distance=>\"0.4 km\", :travel_mode=>\"WALKING\", :travel_type=>nil}, {:duration=>\"12 mins\", :distance=>\"5.3 km\", :travel_mode=>\"TRANSIT\", :travel_type=>\"SUBWAY\"}, {:duration=>\"9 mins\", :distance=>\"0.7 km\", :travel_mode=>\"WALKING\", :travel_type=>nil}]}", "{:out=>[{:duration=>\"10 mins\", :distance=>\"0.7 km\", :travel_mode=>\"WALKING\", :travel_type=>nil}, {:duration=>\"12 mins\", :distance=>\"5.3 km\", :travel_mode=>\"TRANSIT\", :travel_type=>\"SUBWAY\"}, {:duration=>\"6 mins\", :distance=>\"0.4 km\", :travel_mode=>\"WALKING\", :travel_type=>nil}]}"]  

any ideas why? I tried chanign the type of array from :text, to :varchar and got same result. The only solution i found is using eval command to convert string back to array which is not ideal.

Raise an error on Ruby/Script generate scaffold

Posted: 06 Oct 2016 05:27 AM PDT

Hi guys i am currently still learning Ruby. Anyway i am on chapter 13 on web application development.I am stuck at this part for ruby script/generate Entry tittle:string content:text

Based on my research i have came across this link: Why does Ruby "script/generate" return "No such file or directory"?

Apparently i used Rails 3. so this is what happened.I located to my directory i run this command D:\RubyProjects/Part-3/Chapter-13/rails/mydiary> rails generate scaffold Entry title:string content:text

Now i got this error: Bundler could not find compatible version for gem "bundler Current Bundler version: 1.13.2 This Gemfile requires a different version of Bundler.

And i also tried to run this as well: install bundle, gem install bundle

Can anyone help me on this?

How do I search within an JSON array of hashes by hash values?

Posted: 06 Oct 2016 06:37 AM PDT

I am using Postgres' JSON data type to store some information.

For example I have model User with a field locations that holds a json document in the following format:

[{"name": "Location 1", kind: "house"},   {"name": "Location 2", kind: "house"},   {"name": "Location 3", kind: "office"},   ...   {"name": "Location X", kind: "house"}  ]  

I want to query with .where on the JSON data type.

I want to query for users that have at least one location with kind = office.

Thanks!

Wednesday, October 5, 2016

JSON API implmentation for service object in Rails | Fixed issues

JSON API implmentation for service object in Rails | Fixed issues


JSON API implmentation for service object in Rails

Posted: 05 Oct 2016 07:44 AM PDT

As you know, service object is used to create data for multiple domains, or connect 3rd party APIs in one procedure.

So in this case, resource interface and domain model are not exactly matched.

For example, you want to create Subscription. The procedure is following,

  1. create User
  2. create choose the Plan
  3. create Subscription (connecting third party API)

    • If something fails, the rollback occurs.

The business logic is across more than one domain. So I could do POST with those JSON data.

{"plan_id": 1,   "user_info":{"uuid": "644e1dd7-2a7f-18fb-b8ed-ed78c3f92c2b",                "name": "John Doe",                "email": "john@gmailcom"},   "user_card_info": {"object":"card",                      "exp_month": 12,                      "exp_year": 2020,                      "number": 4242424242424242}   }  

In this case, how should I handle this situation in JSON API. Maybe Should I create abstract resource? Also How can I handle this within Controller in JSON API?

Animation firing twice when visiting a cached page by Turbolinks 5

Posted: 05 Oct 2016 07:50 AM PDT

I'm using Animate.css and I have a div with the animated and fadeIn classes. The div fades in fine on initial visit, but when it's visited a second time (i.e. once the page is already cached by turbolinks), the fadeIn animation occurs twice -- once when the cache preview is shown (this happens instantly), and once after the page is actually loaded. How can I fix this and make the animation run only once?

application.js

//= require jquery  //= require bootstrap-sprockets  //= require jquery_ujs  //= require turbolinks  //= require_tree .  

Looking for Ruby on Rails Process Engine

Posted: 05 Oct 2016 07:27 AM PDT

I am looking for a Process Engine for Ruby on Rails or a another way to solve my problem.

When I am thinking of a Process Engine I mean something like Activiti for Java with Spring Boot.

I want something where I can:

  • Implement state-machine like processes (For example in BPMN2.0 process or as Class)
  • Instances of processes are always persisted.
  • I can add delays or waiting conditions to jumps from one state to the other or timeouts on waits etc...
  • (Optional) I can have a system to deploy new versions of my processes into a live system. (Old versions keep running until finished)

I need this to model users for example doing a WebApp assisted activity over the course of a day, where I need to enact escallations wherever necessary.

For example: Go do Job A and enter Code X. If code X hasn't arrived 2 hours later, do Escallation M, otherwise depending on code go do Job B or Job C. And all this can only till a certain time of the day it was started or do Escallation N.

Rails 5 Paranoia - How can I 'show' a deleted record?

Posted: 05 Oct 2016 07:45 AM PDT

Upon soft-deleting a record, I'm unable to call it on the show action on the controller, for it looks for a record matching the record's ID WHERE deleted_at IS NULLL, which is correct given the purpose of the gem, but I'd still like to be able to access it on a sort of a "readonly" state, within the application, in order to allow the user to review the archive and possibly restore it.

How can I work around the deletion scope so that I can access the object again?

New gateway for active merchant gem

Posted: 05 Oct 2016 06:46 AM PDT

I have a new gateway, and this is not in the active merchant option, for security reasons and time y can not include it, I want to use the active merchant gem and in my project folder have this new gateway, What can I do?

Today I have a complete active merchant in my rails proyect in a lib folder and puts my gateway inside the folder, I am make some others configurations and it works for me, but the process is very cumbersome to maintain and update this gem...

Ambiguous match, found 2 elements matching css - Capybara

Posted: 05 Oct 2016 07:11 AM PDT

I have a that renders two of the same elements on the page. I understand what the problem is with the error but I'm just not sure how to fix it? Here is my test:

TEST

 it "deletes the correct snitch" do          user    = login_user          snitch  = create(:snitch, :healthy, owner: user.accounts.first)          snitch2 = create(:snitch, :healthy, owner: user.accounts.first)            visit root_path          delete = page.find(".icon-delete")          first(delete).click          expect(page).to have_content("Please confirm this delete.")       end  

ERROR

 Managing snitches deleting a snitch from the index page deletes the correct snitch   Failure/Error: delete = page.find(".icon-delete")     Capybara::Ambiguous:     Ambiguous match, found 2 elements matching css ".icon-delete"  

How can I pick just one of the icon delete on the page?

Rails exception_handler gem

Posted: 05 Oct 2016 06:43 AM PDT

I've installed Rails excpetion_handler and tried following the instructions to setup custom error handling, however I'm still getting the standard 500 error message that the gem creates:

500 Internal Server Error If you are the administrator of this website, then please read this web application's log file and/or the web server's log file to find out what went wrong.

Here's what I added to config/application.rb:

class Application < Rails::Application    config.exception_handler = {        dev: true,        layouts: {          '500' => 'exception'        }    }  end  

I created an exception layout at layouts/exception.html.erb:

<!DOCTYPE html>  <html>    <head>      <title><%= "Error - #{@exception.status} Error" %></title>    </head>      <body>        <div class="container">        <%= yield %>      </div>      </body>  </html>  

And generated the default exception views with: rails generate exception_handler:views

<div class="error">      <% if /^(5[0-9]{2})$/ =~ @exception.status.to_s %>            <!--Message -->          <%= content_tag :div, class: "message" do %>              <%= content_tag :div, class: "title" do %>                  <span><%= "#{@exception.status} Error - #{details[:name]}" %></span>                  <%= link_to image_tag("exception_handler/close.png"), main_app.root_url, title: "Close (Go back home)", class: "close" %>              <% end %>                <%= content_tag :div, class: "details" do %>                  <%= image_tag "exception_handler/alert.png", title: "#{@exception.status} Error" %>                  <div class="status"><%= @exception.status %> Error</div>              <% end %>                <%= content_tag :div, class: "info" do %>                  <span><%= details[:description] %></span>                  <div class="notification">                      <%= link_to image_tag("exception_handler/home.png", title: "Go Back Home"), main_app.root_url, class: "home" %>                      <div class="version">v<%= Rails.version %></div>                      <strong>Our developers have been notified - we're working on it!</strong>                  </div>              <% end %>            <% end %>        <% else %>            <%= content_tag :div, details[:description], class: "message" %>        <% end %>  </div>  

I've tried restarting my rails server just to make sure the changes are taking effect, but it still doesn't work. What have I missed?

Why do all my radio buttons share a single selection?

Posted: 05 Oct 2016 07:34 AM PDT

I'm trying to build a survey app and I've hit a roadblock. When I'm submitting a response to a survey, all my answers share the same radio button selection id which means that I can only select one radio button across multiple questions whereas I want this to be one radio button per question.

I'm baffled and would very much appreciate some help.

I'm using simple_form for this project.

views/responses/_form.html.erb

<%= @response %>  <%= @response.survey_id %>    <%= @survey.name %>    <p>    <strong>Name:</strong>    <%= @survey.name %>  </p>    <p>    <strong>End date:</strong>    <%= @survey.end_date %>  </p>    <p>    <%= simple_form_for [@survey, @response] do |f| %>      <!-- Survey id -->      <%= f.hidden_field :survey_id, :value => @survey.id %>          <!-- Questions -->        <ol>          <% @survey.questions.each do |q| %>            <li><%= q.content %></li>              <!-- Iterate through answers for this question -->            <%= f.simple_fields_for :answers do |a| %>              <%= f.association :answers, collection: q.answers, as: :radio_buttons, :item_wrapper_class => 'test_class', include_blank: false %>            <% end %>            <% end %>        </ol>          <%= f.submit %>    <% end %>  </p>  

Models

survey.rb

class Survey < ApplicationRecord    has_many :questions, :dependent => :destroy    has_and_belongs_to_many :responses      validates_presence_of :name    accepts_nested_attributes_for :questions, allow_destroy: true  end   

question.rb

class Question < ApplicationRecord    belongs_to :survey, optional: true    has_many :answers, :dependent => :destroy    accepts_nested_attributes_for :answers, allow_destroy: true  end  

answer.rb

class Answer < ApplicationRecord    belongs_to :question, optional: true    belongs_to :response, optional: true      def to_label      "#{content}"    end  end  

response.rb

class Response < ApplicationRecord    belongs_to :survey, optional: true    belongs_to :user, optional: true      has_and_belongs_to_many :answers, :dependent => :destroy  end  

Thanks, Bhams

Edit:

Generated HTML

<p>    <form novalidate="novalidate" class="simple_form new_response" id="new_response" action="/surveys/9/responses" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="39QorGeTDhu7pojy3L6gbZ1GZh9yBhqZphFMRWD++Ghd2ScWeLVEcdyhD9Ym0JyKHLptghvLOnJP9UlmHn32Bw==" />      <!-- Survey id -->      <input value="9" type="hidden" name="response[survey_id]" id="response_survey_id" />          <!-- Questions -->        <ol>            <li>222</li>              <!-- Iterate through answers for this question -->                <div class="input radio_buttons optional response_answers"><label class="radio_buttons optional">Answers</label><input type="hidden" name="response[answer_ids]" value="" /><span class="radio test_class"><label for="response_answer_ids_35"><input class="radio_buttons optional" type="radio" value="35" name="response[answer_ids]" id="response_answer_ids_35" />11111</label></span><span class="radio test_class"><label for="response_answer_ids_36"><input class="radio_buttons optional" type="radio" value="36" name="response[answer_ids]" id="response_answer_ids_36" />2222</label></span><span class="radio test_class"><label for="response_answer_ids_37"><input class="radio_buttons optional" type="radio" value="37" name="response[answer_ids]" id="response_answer_ids_37" />33333</label></span><span class="radio test_class"><label for="response_answer_ids_38"><input class="radio_buttons optional" type="radio" value="38" name="response[answer_ids]" id="response_answer_ids_38" />444444</label></span><span class="radio test_class"><label for="response_answer_ids_39"><input class="radio_buttons optional" type="radio" value="39" name="response[answer_ids]" id="response_answer_ids_39" />55555</label></span></div>              <li>33333333333</li>              <!-- Iterate through answers for this question -->                <div class="input radio_buttons optional response_answers"><label class="radio_buttons optional">Answers</label><input type="hidden" name="response[answer_ids]" value="" /><span class="radio test_class"><label for="response_answer_ids_40"><input class="radio_buttons optional" type="radio" value="40" name="response[answer_ids]" id="response_answer_ids_40" />4444444444444</label></span><span class="radio test_class"><label for="response_answer_ids_41"><input class="radio_buttons optional" type="radio" value="41" name="response[answer_ids]" id="response_answer_ids_41" />55555</label></span></div>          </ol>          <input type="submit" name="commit" value="Create Response" data-disable-with="Create Response" />  </form></p>  

Non specific MVC framework ruby gems and example code to Rails framework

Posted: 05 Oct 2016 06:43 AM PDT

I have been learning Ruby on Rails, but I still have issues when it comes to Ruby gems with examples that are irb based and not Rails or Sinatra framework based. I am trying to implement the Block.io Bitcoin API functionality. But the code I find is Ruby only, so I am not sure where to create a config file for the API Key and also whether I need to create a controller to make this work in the views for Rails.

The gem and examples are on: https://github.com/BlockIo/gem-block-io

I installed this gem via bundle install on Rails

gem install block_io -v=1.0.6  

The Ruby example show the following:

>> require 'block_io'  >> BlockIo.set_options :api_key=> 'API KEY', :pin => 'SECRET PIN', :version => 2  

In Rails which config file would I enter the above api_key and pin?

In the example they show the code to get your address as follows:

BlockIo.get_my_address  

Do I need to create a function in a controller such as:

def address   @my_address = BlockIo.get_my_addresses  end  

and in the view use:

<%= @my_address %>  

I need some guidance with regards to the above, any comment or assistance will be greatly appreciated.

Validate, prefill and potentially block while typing

Posted: 05 Oct 2016 05:56 AM PDT

I have a field where user has to fill in their social security number.

If the users birthdate is the 14th of November 1990

The social security starts with 90.11.14-XXX.XX (X represents random number 0-9)

I'm using simple_form

<%= f.input :ssn,               label: t('employee.social_security_no'),              input_html: { placeholder: "XX.XX.XX - XXX.XX" }%>  

I would like to achieve the following:

1) How can I preset the input field set with 90.11.27-_ _ _ . _ _

2) and validate that the remaining 5 numbers are actually numbers

3) and limit the field so that user cannot fill in more than 5 extra digits.

Any help to get me on the way is greatly appreciated.

Not able to use "number_with_precision" in ApplicationHelper's method in Rails 5.0

Posted: 05 Oct 2016 06:33 AM PDT

i am using "number_with_precision" method in Rails View, it is working fine there, for example:

In Rails View: (Works Fine)

<%= number_with_precision(job.company.rating, :precision => 2) %>  

But when i try to do the same in ApplicationHelper's method then it gives me the following error: undefined method `number_with_precision' rails

here is what i have tried:

In Rails ApplicationHelper: (Gives Error)

module ApplicationHelper      def employer_overall_rating(overall_rating)        @overall_rating = number_with_precision(overall_rating, :precision => 2)    end    end  

Please let me know how i can use the same in ApplicationHelper.

Thanks.

Javascript is not executed

Posted: 05 Oct 2016 05:44 AM PDT

i cant figure out, why my javascript is not executed (and its really not executed).

/app/assets/javascripts/application.js:

//= require jquery  //= require bootstrap-sprockets  //= require turbolinks  //= require jquery_ujs  //= require_tree .  

/app/controllers/project_controller.rb:

def upload      @projects = Project.all.order(updated_at: :desc)      @project = Project.find(params[:id])      respond_to do |format|          format.html          format.js {render layout: false}      end  end  

/app/views/projects/show.html.erb:

<%= link_to project_upload_path, :project => @project.id, class: "btn btn-default" do %>      Upload &nbsp;      <%= glyph("plus") %>  <% end %>  

/app/views/projects/upload.html.erb:

<div class="row">      <div class="col-xs-12">          <h2>Upload File to <%= @project.name %> project</h1>      </div>      <br>      <div class="col-xs-12">          <%= render :partial => "uploadform", :action => "savefile" %>      </div>  </div>  

/app/views/projects/_uploadform.html.erb:

<%= form_for :upload, url: {action: "savefile"}, :multipart => true  do |f| %>      <%= f.hidden_field(:project_id, :value => params[:id]) %>      <%= f.file_field :file, input_html: { hidden: true }, label: 'Upload Attachment'  %>      <input id="file-display" class="input-large uneditable-input" type="text">      <%= f.submit "Save File", :class => "btn btn-default btn-file", :id => "upload-btn" %>  <% end %>  

/app/views/projects/upload.js.erb:

$(document).on('ajax:success', function() {      alert("Test");  });  

I tried everything. I added and removed "{render layout: false}" in my controller. I tried "page:change" and "turbolinks:load" in my upload.js.erb (instead of "ajax:success"). I tried all of the Java-Ready functions in "_uploadform.js.erb" (instead of "upload.js.erb"). I tried "remote: true" in link_to (show.html.erb) - but then it only executes js.erb (just the alert came up). I also updated Rails from 4.2.1 to 4.2.7.1 and tried "//= require jquery.turbolinks" in application.js (with all the document ready functions above).

As you can see in my log, it seems that it doesnt respond with the Javascript:

Started GET "/projects/upload/20" for 127.0.0.1 at 2016-10-05 14:05:48 +0200  Processing by ProjectsController#upload as HTML    Parameters: {"id"=>"20"}    Project Load (0.0ms)  SELECT  "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1  [["id", 20]]    Rendered projects/_uploadform.html.erb (0.0ms)    Rendered projects/upload.html.erb within layouts/application (2.4ms)  Completed 200 OK in 327ms (Views: 324.8ms | ActiveRecord: 0.0ms)  

Please help me. I dont understand why this is not working in any way.

Get progress of AJAX call to get JSON in Rails

Posted: 05 Oct 2016 05:45 AM PDT

I have the following JS to retrieve some JSON data from a controller method in a Rails app:

$.ajax({      xhr: function() {          var xhr = $.ajaxSettings.xhr();          xhr.onprogress = function(e) {              if (e.lengthComputable) {                  console.log(e.loaded / e.total);              }          };          xhr.upload.onprogress = function(e) {              if (e.lengthComputable) {                  console.log(e.loaded / e.total);              }          };          return xhr;      },      cache: false,      url: '/get_data',      method: 'GET',      dataType: 'JSON',      success: function(data) {          console.log(data);      }  });  

And the method is as follows:

def get_data    @data = [{....}]    respond_to do |format|      format.html      format.json do        render json: @data      end    end  end  

The method can take up to 3-4 seconds to return due to the @data being either large or requiring complex calculations first, so I want to show a progress bar whilst the AJAX is taking place.

Note: I don't just want to show a loader that shows before and after the AJAX, but actually show the progress!

However I'm finding that lengthComputable is always false...

How can I get Rails to send back the correct progress?

Ruby on Rails - multiple database connections

Posted: 05 Oct 2016 07:13 AM PDT

I'm developing an application where it lets users to establish many number of database connections with a has-many relationship between user and connections. The connections are passive until the user manually connects each. The motive is to perform queries on them, parallely.

I don't find good tutorials related to this, can you help me with some tips on how to accomplish this ?

Couldn't find record without an ID, Rails 4 and ActiveAdmin

Posted: 05 Oct 2016 05:37 AM PDT

I am implementing ActiveAdmin to CRUD my app's content. So far so good. But I am receiving error: Couldn't find Girl without and ID when I am accessing action 'New' in my admin panel.

enter image description here

My ActiveAdmin controller:

controller do         def create            @advertisement = Girl.new(girl_params)           respond_to do |format|           @advertisement.bypass_humanizer = true             if @advertisement.save                     if params[:images]                   params[:images].each { |image|                      @advertisement.pictures.create(image: image)                    }               end                format.html  {redirect_to admin_girl_path(@advertisement)}              format.json  { render :json => @advertisement, :status => :created, :location => @advertisement }             else               format.html { render :action => "new"  }             format.json { render json: @advertisement.errors.full_messages, status: :unprocessable_entity }           end        end     end        def new       @advertisement = Girl.new     end      def edit      @advertisement = Girl.find(params[:id])    end        def update         @advertisement = Girl.find(params[:id])         flash[:notice] = 'Girl was successfully updated.' if @girl.update(girl_params)             redirect_to :back   end       def show       @advertisement = Girl.find(params[:id])     end      def destroy       @advertisement = Girl.find(params[:id])       @advertisement.destroy                redirect_to :back          end          def girl_params         # NOTE: Using `strong_parameters` gem         params.required(:girl).permit(:id,:humanizer_question_id, :_destroy, :confirmed_at,:bypass_humanizer,:humanizer_answer, :identifier, :token,:name, :work1,:subname,:paid, :work2, :check, :can_add_review,:work3, :work4,:smsidentifier,:smsidentifier_confirmation,:provaider, :expiration,:your_ip,:in_blacklist,:admin_confirmed,:country_id, :region_id,:user_id,:phone_number,:image,:terms_of_service,:region,:age,:height,:weight,:description,:description_ru,:email, hour_ids: [], pictures_attributes: [:image], service_ids: [])      end    end    

I have no clue to start with. I can't see problem.

What I tried:

Changed girl_params to permit_params :id,:humanizer_question_id,... then

def create            @advertisement = Girl.new(permited_params[:girl])    end  

But that didn't solve the issue.

Thanks in advance for any help.

image-path in "*.css.scss" isn't converted to an actual path

Posted: 05 Oct 2016 06:02 AM PDT

I have a css which I've converted to *.css.scss online. I include it into application.css. In my *.css.scss I have this:

background: url(image-path 'something.png') ;  

But it doesn't work because "image-path" isn't converted to the actual path but stays at it is, as a string.

http://localhost:3000/assets/image-path%20%22something.png%22  

The image exists if I enter the path manually.

This throws an exception -- invalid syntax:

background: url(<%= image-path 'something.png' %>) ;  

How to return custom error codes in a Rails API?

Posted: 05 Oct 2016 06:14 AM PDT

Given a RESTful API, implemented in Rails, I want to include in the responses not only the errors messages, generated by ActiveModel::Validations, but also custom error codes. First of all I would like to point out that I am not talking about HTTP Status codes. I am talking about having an error of any type (from general errors like record not found to small validation errors like username can't be blank) be mapped to a unique numeric code, that is custom application-specific error codes. Let me give an example - given a list of error codes, like:

1: record not found  ... some other errors  # Validation errors for User model between 1000 to 2000   1001: first name can't be blank   1002: first name must contain at least 3 characters   1003: last name can't be blank   1004: last name must contain at least 3 characters   ...some other errors  

If I have a form for a user and submit it with empty fields for first and last name, I want to have in the response body something like:

{error_codes: [1001, 1002, 1003, 1004]}  

or something similar (for example I could have an array of error objects, each with a code, message for developer, message for user etc.). Let me give an example with the Twilio API, taken from RESTful API Design: what about errors?:

enter image description here

Here, 20003 is some custom Twilio-specific code. The question is - how can this be implemented in Rails? I see several difficult aspects:

  • how do I get a list of all possible errors that can be encountered. It is hard to get such a list even only for the validation errors, let alone the other types of errors that can occur.
  • how should this list be organized - maybe in a YAML file?
  • how do I access the list - maybe something similar to the way translations are accessed via I18n.t?

I will really appreciate any advice on the topic. Thank you.

P.S. I think this is a similar question.

No SSL caused by mixed content in ruby app

Posted: 05 Oct 2016 04:55 AM PDT

I have an APP written in Ruby. The authentication is made through Facebook-Graph_API.

I am using an SSL certificate which is validated through Globe SSL.

The connection is encrypted and almost everything is working fine. BUT!

The connection is insecure caused by mixed content. The pictures which the app is loading are coming through http. But I need this from an https source.

I found here:

Graph API for Facebook developers

that I have to use something like this:

return_ssl_resource => true

But I don´t know at which Position I have to paste this!

Does anybody have an example or experience with this? I you need further Information please let me know.

Thx for your help!

How to include subdirectories to autoload for Grape API?

Posted: 05 Oct 2016 04:41 AM PDT

I'm using Grape to build an API for a Rails project (I'm mounting the grape project in rails routes.rb something like mount Backend::Base => '/').

The files structure is something like:

├── app │   ├── api │   │   └── backend │   │   ├── base.rb │   │   └── v1 │   │   ├── alerts.rb │   │   ├── test │   │   │   └── index.rb

My application.rb includes:

config.paths.add "app/api", glob: "**/*.rb"    config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')  config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]  

For base.rb:

module Backend    class Base < Grape::API        format :json      prefix :api        mount CanopyBackend::V1::Alerts      mount CanopyBackend::V1::Test::Index      end  end  

My alerts.rb:

module Backend    module V1      class Alerts < Grape::API        include Backend::V1::Defaults          resource :alerts do          get do            "alerts"          end        end      end    end  end  

And test/index.rb:

module Backend    module V1      module Test        class Index < Grape::API          include Backend::V1::Defaults            resource :index do            get do              "index"            end          end        end        end    end  end  

Now it seems I can access GET api/v1/alerts but not api/v1/test/index somehow.

I tried to modify config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] in application.rb to make it config.autoload_paths += Dir[Rails.root.join('app', 'api', '/**/')] but without any luck.

Any help?

Stubbing with WebMock not intercepting request

Posted: 05 Oct 2016 04:40 AM PDT

I'm attempting to stub a request to a Controller using WebMock. However, as I'm creating the stub, the request isn't being intercepted the way I'd expect or want it to be.

The Controller does nothing but render JSON based on the query parameter:

def index          render json: MyThing.search(params[:query]).as_json(only: [:id], methods: [:name_with_path])  end  

And the stubbing goes as follows:

mything_val = { ...json values... }  stub_request(:any, mything_path).with(query: { "query" => "a+thing" }).to_return(body: mything_val, status: 200)  page.find('.MyThingInput > input').set('a thing')    # Note: I've tried this with and without the `query:` parameter, as well as   with and without specifying header info.  

This is triggering a React component. What it does is, when a word or words are entered into the input, it sends an AJAX request to mything_path with the inputted value, which returns as JSON several suggestions as to what the user might mean. These are in a li element within .MyThingInput-wrapper.

In the spec file, I include:

require 'support/feature_helper'  require 'support/feature_matchers'  require 'webmock/rspec'  WebMock.disable_net_connect!  

What's actually happening when I input the text into the React component however is that regardless of the WebMock stub, it's hitting the Controller, making the DB request, and failing due to some restrictions of the testing environment. My understanding of how this should work is that when the request is made to mything_url, it should be intercepted by WebMock which would return the values I pre-defined, and never hit the Controller at all.

My guess is that somehow I'm mocking the wrong URI, but honestly, at this point I'm really uncertain. Any and all input is appreciated, and I'm happy to clarify any points I've made here. Thanks massively!

cap staging deploy: bash: bundle: command not found

Posted: 05 Oct 2016 04:40 AM PDT

I am running my Rails 5 project on CentOS 7 with rbenv. When i run cap staging deploy i got the error:

cd /srv/www/stagings/testproject/current; bundle exec rake db:migrate RAILS_ENV=staging stderr: bash: bundle: command not found    ** DEPLOY FAILED  ** Refer to log/capistrano.log for details. Here are the last 20 lines:      INFO [f7a6296f] Finished in 0.256 seconds with exit status 0 (successful).  

I can run bundle install in deploy directory /srv/www/stagings/testproject/current without any problem.

.bash_profile

PATH=$PATH:$HOME/.local/bin:$HOME/bin  export PATH  export PATH="$HOME/.rbenv/bin:$PATH"  export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"  eval "$(rbenv init -)"  

ruby, gem, bundler versions:

which ruby  ~/.rbenv/shims/ruby  which bundle  ~/.rbenv/shims/bundle'   which gem  ~/.rbenv/shims/gem  

I tried

 gem uninstall bundler   gem install bundler`  

doesn't work. Any help? Thank you very much!

Insert data into junction table

Posted: 05 Oct 2016 04:55 AM PDT

I am trying to insert a set of data into a junction. I want to be able to set the default set of products to every new merchant that is created, then the merchant will have options to set their prices availability etc based on their needs.

I have the current method define

def add_products    @product = Product.all    @product.each do |product|      @merchant = MerchantProducts.create!(product_id: product.id, merchant_id: self.id)    end  end  

problem I am getting is the below

uninitialized constant Merchant::MerchantProducts  

Error with instance variable in Index view

Posted: 05 Oct 2016 05:17 AM PDT

So in my tutors_controller.rb this is my index action

  def index      @tutor = Tutor.all      @tutor = @tutor.fees_search(params[:fees_search]) if params[:fees_search].present?    end  

and in my index.html.erb this is the view

<div class='container'>    <%= form_tag(tutors_path, method: :get) do %>      <%= label_tag 'fees_search', 'Max Fees' %>      <%= select_tag 'fees_search', options_for_select((10..50).step(10)) %>      <%= submit_tag 'Filter' %>    <% end %>    <% @tutor.each do |tutor| %>      <% unless tutor.admin? %>        <div class='row' id='tutor-listing'>          <div class='col-xs-4'>            <%= image_tag(tutor.profile.avatar.url, :class => "img-rounded" ) if tutor.profile.avatar? %>          </div>          <div class='col-xs-8'>            <h3><%= link_to tutor.full_name, tutor_path(tutor) %></h3>            <% unless tutor.subjects.nil? %>              <% tutor.subjects.each do |subs| %>                  <span class='badge'id='tutor-listing-badge'>                    <%= link_to subs.name, subject_path(subs) %>                  </span>              <% end %>            <% end %>            <% unless current_tutor %>              <%= button_to "Shortlist Tutor", add_to_cart_path(tutor.id), :method => :post %>            <% end %>          </div>        </div>       <% end %>    <% end %>  </div>  

So i understand that when the index view first renders, @tutor would simply be Tutor.all so it renders each individual tutor perfectly.

After trying to filter it though, i start receiving errors. The exact error is NoMethodError in Tutors#indexand the highlighted line is <% unless tutor.admin? %>

enter image description here

profile.rb model

class Profile < ActiveRecord::Base    belongs_to :tutor    scope :fees_to, -> (fees_to) { where("fees_to <= ?", "#{fees_to}") }  end  

tutor.rb model

class Tutor < ActiveRecord::Base    has_one :profile, dependent: :destroy    def self.fees_search(n)      @profile = Profile.fees_to(n)      if @profile.empty?        return Tutor.none      else        @profile.each do |y|          y.tutor        end      end    end  end  

I get that now my @tutor instance variable has obviously changed. But how do i go about resolving this problem? Should i be rendering a partial instead? Obviously my index action in my controller could be "better" also but i'm quite confused now as to what i should be doing.

Would appreciate any advice! Thank you!

How to test a method that filters on several conditions?

Posted: 05 Oct 2016 04:49 AM PDT

I'd like to improve specs for a convenience method that returns an array of users whose purchases are due tomorrow and will be paid using a certain payment method (ignoring other payment methods).

The specs are something along the lines of:

it "doesn't return users without purchases being due tomorrow" do    # create user and associated records that don't fit the time condition    expect(subject).to eq([])  end    context "with users who have purchases due tomorrow" do      it "returns users with $CERTAIN_PAYMENT_METHOD" do      # create different users with different payment methods,      # all matching the time condition.        expect(subject).to eq([user_1, user_2])    end        it "doesn't return users without $CERTAIN_PAYMENT_METHOD" do      # create user with credit card,      # matching the time condition.        expect(subject).to eq([])    end    end  

I see three possible approaches here:

  1. Approach used above: Set up arbitrary combinations of records, and expect things specific to a single condition, always asserting the whole array. The setup can be long and repetitive.
  2. Set up arbitrary combinations, and expect things to be included/excluded in the returned array. These "soft expectations" are great to read but can be very error-prone.
  3. Set up (nearly) all combinations of records, and have a single expectation. This creates no overlap but also leaves developers in the dark as to why this method returns this specific array.

All approaches have their drawbacks, and I'm wondering if there's a best practice how to test methods like these?

cucumber does not recognize my steps

Posted: 05 Oct 2016 04:08 AM PDT

Feature: Home page  As a HR manager of a company I am visiting the digipresent app for the first time  I want to be welcomed with a greeting         Scenario: User sees the welcome message          When: he goes to home page          Then: he should see the welcome message  

This file is named as features/home_page.feature

When (/^he goes to the home page$/) do       visit root_path  end    Then (/^he should see the welcome message$/)do       expect(page).to have_content("Welcome to Present")  end  

This file is present as features/step_definitions/home_page_steps.rb

$cucumber --require features features/home_page.feature when I do this, the steps are not getting recognised.

Feature: Home page  As a HR manager of a company I am visiting the digipresent app for the first time  I want to be welcomed with a greeting       Scenario: User sees the welcome message # features/home_page.feature:5          When: he goes to home page          Then: he should see the welcome message    1 scenario (1 passed)  0 steps  0m0.023s  

How to call multiple bash command and ssh in Ruby?

Posted: 05 Oct 2016 04:01 AM PDT

I want to do the following commands in ruby.

  1. ssh into another computer using ssh example@example
  2. set source file source ~/.profile
  3. cd to/some/folder
  4. call my shell script with parameters, a json formatted string ,./my_script.sh my_hash.to_json

However I am facing these problems: I call them in one line using backticks, it works, but it is a very bad practice in my opinion because it is not readable nor it is maintainable.

On the other hand, when I call my_hash.to_json, the resulted string has non-escaped double quotes, How do I escape them?

how to use ur friendly / slug properly in rails routes?

Posted: 05 Oct 2016 03:23 AM PDT

i have a table which i generated with scaffold, something like this

rails generate scaffold Book title:string year:integer etc...

only admin can access above table with url something like :

admin/books/book-1
admin/books/book-2

i use friendlyid gem to generate slug value, and i don't have problem with that.

but now i need to access a page in public and query book data based on slug string, i really have no idea how to make route accept an url like this :

public/book-1  

currently i do it with query string : public?book_id=123 and get the parameters like this : Book.where(:id=>params[book_id]) and i need to change it with slug way?

i tried to add this to my route file, but still no luck

# get 'public/:slug', to: 'public#detailed_book', as: 'slugged_post'  

please advice, kindly show me how to setup my route file correctly and how to get the parameter in controller.

Rubymine - code folding ALL rspec examples

Posted: 05 Oct 2016 03:03 AM PDT

Does anyone know if it's possible to code fold all rspec examples either automatically on opening a spec file or preferably by key binding from within Rubymine.

For a spec with lots of examples it would be very handy to just collapse all examples to get an overview of the complete spec for a model, controller, etc. This would make it far easier to review and check for any missing edge conditions for example.

What I would like is for the it block to code fold so that they result in something like...

it 'should blah blah blah' do ... end

... without having to manually code fold every individual example.

no implicit conversion of Pathname into String in login with google+ api

Posted: 05 Oct 2016 03:13 AM PDT

I am trying to implement login with Google+ Api with Omniauth.

sample code- omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do  provider :google_oauth2, Rails.application.secrets.google_client_id,        Rails.application.secrets.google_client_secret  end  

secrets.yml

 development:     secret_key_base:81953bc9411692c38d1224b39cf5bc0084290fef92     google_client_id: f30mofk10me.apps.googleusercontent.com      google_client_secret: *********************      test:       secret_key_base:   afa40d5824fee961dcd1a598axxxxxxxxxxxxxxxxx    production:      secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>     google_client_id: <%= ENV["GOOGLE_CLIENT_ID"] %>     google_client_secret: <%= ENV["GOOGLE_CLIENT_SECRET"] %>  

Session controller.rb

 class SessionsController < ApplicationController        def create      auth = request.env["omniauth.auth"]      puts auth      session[:omniauth] = auth.except('extra')      user = User.sign_in_from_omniouth(auth)      session[:user_id] = user_id      redirect_to root_url, notice:"Sign In"  end  def destroy      session[:user_id] = nil      session[:omniauth] = nil      redirect_to root_url, notice:"Sign OUT"  end      end  

user.rb

   class User < ActiveRecord::Base     def self.sign_in_from_omniouth(auth)     find_by(provider: auth['provider'], uid: auth['uid'])||      create_user_from_omniauth(auth)    end     def self.create_user_from_omniauth(auth)    create(      provider:auth['provider'],      uid:auth['uid'],      name:auth['info']['name']  )    end  

end

Home controller.rb

class HomeController < ApplicationController    before_action :set_auth     def index    end     def profile    end    private    def set_auth  @auth = session[:omniauth] if session[:omniauth]  end  end  

Application controller.rb

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception     private    def current_user  @current_user ||= User.find(session[:usr_id]) if session[:user_id]  end   helper_method :current_user   end  

Application.html.rb

 <ul class="nav navbar-nav navbar-right">   <% if current_user %>      <li>Signed in as:<%= current_user.name %> - <%= image_tag(@auth['info'] ['image'],width: '50',height:'50',class: 'img-circle') %></li>      <li><%= link_to "Sign Out", 'sign_out', method: :delete %></li>    <%else%>      <li>    <%= link_to(image_tag("Fecebook_logo.png", width:40,hight:40), "auth/facebook") %></li>      <li>    <%= link_to(image_tag("googleplus2.png", width:40,hight:40), "auth/google_oauth2") %></li>      <li>  <%= link_to(image_tag("twitter.png", width:40,hight:40), "auth/twitter") %></li>     <%end%>   </ul>  

after all this set up i want to log in with google.It call to the redirected url http://localhost:9292/auth/google_oauth2/callback enter image description here

after allow that above error msg return...what should i do? thanks in advance

Using aggregate with options allowDiskUse in Mongoid

Posted: 05 Oct 2016 02:52 AM PDT

Problem:

My memory is getting exceeded while using sort in MongoDB query and tells me to use allowDiskUse:true option in the query. But in rails mongoid, aggregate function is not passing any options.

The error I am getting:

Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true to opt in. (16819)  

My Code/Query:

result = ModelName.collection.aggregate([        {"$sort" => {            "created_at" => 1        }}      ], {'allowDiskUse' => true})  

My Objective:

To use allowDiskUse option in the mongoid query so that I can get the sorted data by created time but mongoid does not support it I guess, so I need some alternative. Any suggestions on what I should do ?