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!

No comments:

Post a Comment