Tuesday, June 28, 2016

Cohort analysis using pgsql/activerecord | Fixed issues

Cohort analysis using pgsql/activerecord | Fixed issues


Cohort analysis using pgsql/activerecord

Posted: 28 Jun 2016 07:57 AM PDT

I'm performing a cohort analysis on a single table messages. I need to calculate the retention rates of users that created a message (day_0), also created a message on the following day, day after, etc (day_1, day_2, etc).

I was previously doing most of the processing post-query in ruby iterations. Now I have larger tables to deal with. It's way too slow and memory intensive in ruby so I need to offload the heavy lifting to the DB. I've also tried the cohort_me gem and experienced poor performance.

I don't have much experience with SQL w/out activerecord. Here's what I have so far:

SELECT   date_trunc('day', messages.created_at) as day,  count(distinct messages.user_id) as day_5_users  FROM   messages  WHERE   messages.created_at >= date_trunc('day', now() - interval '5 days') AND   messages.created_at < date_trunc('day', now() - interval '4 days')  GROUP BY 1  ORDER BY 1;  

This returns the count of users who created messages five days ago. Now I need to find the count of THOSE users who created messages the following day, day after that, etc. until the current day.

I need to perform this same analysis on different base days. So next instead of 5 days go, it starts the analysis at 4 days ago as the base day.

Can this be done with one query?

Implementing .each in Wicegrid (Ruby on Rails)

Posted: 28 Jun 2016 07:54 AM PDT

I have the following column in my Wicegrid table, which iterates through the advisors of a student and lists them in the Wicegrid:

g.column name: 'Student Advisor' do |user|    res=''    if user.advisors      user.advisors.each do |advisor|        advisor.username      end    end   end  

Wicegrid doesn't allow arrays to be returned inside their columns or at least that is what I understood from the error below:

"When WiceGrid column block returns an array its second element is expected to be a hash containing HTML attributes for the tag."

Is there another way to have the list of advisors in the table?

CSS animation not working in Rails app

Posted: 28 Jun 2016 07:46 AM PDT

So I have a button that I want to auto-hide when the user scrolls down the page and show when the user scrolls up. Below are the codes:

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require bootstrap-sprockets  //= require turbolinks  //= require_tree .  //= require jquery.infinitescroll  

index.html.haml

%a.scrollToTop{:href => "#"}  

autohide.js

$(document).ready(function(){      var prev = 0;    var $window = $(window);    var bar = $('.scrollToTop');      $window.on('scroll', function(){      var scrollTop = $window.scrollTop();      bar.toggleClass('hidden', scrollTop > prev);        prev = scrollTop;    });    });  

application.css.scss

/*   *= require_tree .   *= require_self   */    // "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"  @import "bootstrap-sprockets";  @import "bootstrap";      .scrollToTop{    width:70px;    height:70px;    background: #fff;    font-weight: bold;    position:fixed;    bottom:20px;    right:20px;    border-radius:50%;    box-shadow: 0 2px 5px rgba(0,0,0,0.12), 0 2px 4px rgba(0,0,0,0.24);    -webkit-transform: translateZ(0);    transition: transform 1s  }    .scrollToTop:hover{    box-shadow: 0 10px 20px rgba(0,0,0,0.25), 0 8px 8px rgba(0,0,0,0.22);    -webkit-transition: all 0.4s ease-in-out;    -moz-transition: all 0.4s ease-in-out;    -o-transition: all 0.4s ease-in-out;    transition: all 0.4s ease-in-out;  }    .scrollToTop.hidden{    transform: translateY(100px);  }  

The code works fine; the button does hide/show depending on the scroll direction. But the problem is, it doesn't animate i.e. it instantaneously hides and shows instead of sliding up and down. Any idea what's causing this? Thanks in advance!

Run a Rails job at precise time (accurate to the second)

Posted: 28 Jun 2016 07:40 AM PDT

I'm making an application that needs to run a job at extremely precise intervals of time (say 30 seconds, maximum acceptable delay is +-1 second).

I'm currently doing so using an external Go application that polls an API endpoint built within my application.

Is there a way that I could run the task on a worker machine (eg a Heroku dyno) with delays less than one second?

I've investigated Sidekiq and delayed_job, but both have significant lag and therefore are unsuitable for my application.

omniauth instagram oauth2 code 400

Posted: 28 Jun 2016 07:34 AM PDT

this is my gem file :

gem 'omniauth-oauth2', '1.4'  gem 'omniauth-instagram', github: 'ropiku/omniauth-instagram'  

omniauth.rb file :

Rails.application.config.middleware.use OmniAuth::Builder do  provider :instagram, ENV['Client ID'], ENV['secret']  end  

this is sesstion.rb

class SessionsController < ApplicationController  def new  redirect_to '/auth/instagram/'  end     def create  auth = request.env["omniauth.auth"]  user = User.where(:provider => auth['provider'],                    :uid => auth['uid'].to_s).first || User.create_with_omniauth(auth)  reset_session  session[:user_id] = user.id  redirect_to root_url, :notice => 'Signed in!'    end     def destroy  reset_session  redirect_to root_url, :notice => 'Signed out!'   end      def failure       redirect_to root_url, :alert => "Authentication error: #{params[:message].humanize}"    end     end  

but when i click on sign in i face this error

{"code": 400, "error_type": "OAuthException", "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}  

and this is url : https://www.instagram.com/oauth/authorize?client_id&redirect_uri=http://localhost:3000/auth/instagram/callback&response_type=code&scope=basic&state=955173070b58f0de9affcdb30c0da27d836683b922542db1

what is my problem ?

fonts and images and not loading

Posted: 28 Jun 2016 07:43 AM PDT

I have deploy my application on AWS with nginx and passenger .My images, fonts and icons are not loading .I have look for the possible solution on internet like config.assets.compile = true and did RAILS_ENV = 'production' rake assets:precompile but nothing working for me

Difference between ActiveRecord::Base.connection and find_by_sql

Posted: 28 Jun 2016 07:31 AM PDT

I need to perform some custom queries on my rails application and was wondering wich approach is better:

results = ActiveRecord::Base.connection.execute(query)  

Or

Model.find_by_sql(query)  

Been reading the documentation but didn't really get how they perform.

Ajax request to rails controller is setting the id parameter = "destroy"?

Posted: 28 Jun 2016 07:31 AM PDT

so I have a weird problem where for some reason the id parameter in my delete request is being set to "destroy". Here is the code for my ajax request

function deleteItems(id_data, table){    $.ajax({      url: '/items/destroy',      method: 'DELETE',      processData: true,      data: {ids: id_data },      success: function(){       dropItems(id_data, table)      }    });   }  

And here are the parameters I am getting in the rails controller

{"ids"=>["6", "19"], "controller"=>"items", "action"=>"destroy", "id"=>"destroy"}  

If I try and set the data key to id (instead of id's) I get this

{"id"=>"destroy", "controller"=>"items", "action"=>"destroy"}  

Any help in figuring out why id is being set to "destroy" would be awesome. Thanks

How to use ruby uniq on nested array/hash

Posted: 28 Jun 2016 07:37 AM PDT

I am trying to call the uniq method on the follow json so that it would only return unique result base on employee_id

# Json array  a ={    results: [     {      employee: {        name: "A",        employee_id: "A-00016",        title: 1       }     },{      employee: {        name: "A",        employee_id: "A-00016",        title: 2       }     },{      employee: {        name: "C",        employee_id: "C-00017",        title: 3       }      }     ]    }        # Calling uniq on a  a.uniq { |p| p.values_at(:employee_id) }  

However, I am only getting this result

{    results: [     {      employee: {        name: "A",        employee_id: "A-00016",        title: 1       }      }     ]    }  

Instead of what I want

{    results: [     {      employee: {        name: "A",        employee_id: "A-00016",        title: 1       },{      employee: {        name: "C",        employee_id: "C-00017",        title: 3       }      }     ]    }  

Am I using the correct method to output the result I want?

How to read from Rails cache atomically

Posted: 28 Jun 2016 07:17 AM PDT

I have 2 processes running. The user action that basically does this:

      Rails.cache.fetch("items/#{self.id}/default_as_json") do          super(root: false,                :only => get_only_show,                :methods => get_include_methods          )        end  

On page load

Then I have another process, that does not run as often. Maybe once every 2 weeks, but it runs for a couple hours.
This process is doing a lot of data processing and after a lot of testing the best option I came up with was just to clear the entire cache after each step. So the website served the most up to date information. The performance cost of this is not much of an issue.
I am essentially running into a race condition on page load. It seems like it is finding the existence of the key, but by the time it goes to read the key the file has been deleted.
This is the stack trace I am seeing when this happens:

ActionView::Template::Error (No such file or directory @ rb_sysopen - [CACHE_LOCATION]/A95/DD0/.permissions_check.70057658850120.4451.366289):      43:       <% if object_type == "Item" %>      44:         <%= render(      45:           partial: 'items/no_table_row',      46:           locals: {object: this_object.as_json,      47:                   singlesearch: true}      48:         ) %>      49:       <% elsif object_type == "Ability" %>    app/models/item.rb:202:in `serializable_hash'    app/views/poly_single_searches/_search_list.html.erb:46:in `block in _app_views_poly_single_searches__search_list_html_erb__1164541304050581354_70057643074520'    app/views/poly_single_searches/_search_list.html.erb:35:in `_app_views_poly_single_searches__search_list_html_erb__1164541304050581354_70057643074520'    app/views/poly_single_searches/fetch_search.html.erb:1:in `_app_views_poly_single_searches_fetch_search_html_erb___2217227932112086773_70057643107440'    app/controllers/poly_single_searches_controller.rb:14:in `fetch_search'        Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.8ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.0ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (7.5ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.6ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.5ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.7ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.5ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (11.0ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.3ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.4ms)    Rendered /home/jon/.rvm/gems/ruby-2.1.2/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (26.0ms)  

When this other process is not running, everything works perfectly. I have it as a task to figure out a better way to clear caching, right now not clearing the cache after each step is not an option.
One solution I have is wrapping the Rails.cache.fetch in a rescue for this however that may just keep failing until it manages to run fast enough.

Errno::EMFILE (Too many open files - socket(2)) when using RedisStore for caching while running in Passenger

Posted: 28 Jun 2016 07:11 AM PDT

My application is using the redis store, which works fine locally, but in production, using Phusion Passenger (open source) I run into this error.

Errno::EMFILE (Too many open files - socket(2)):  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:24:in `initialize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:24:in `initialize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:143:in `new'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:143:in `connect_addrinfo'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:187:in `block in connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:185:in `each'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:185:in `each_with_index'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:185:in `connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:260:in `connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:336:in `establish_connection'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:101:in `block in connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:293:in `with_reconnect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:100:in `connect'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:364:in `ensure_connected'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:221:in `block in process'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:306:in `logging'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:220:in `process'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis/client.rb:120:in `call'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:862:in `block in get'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:58:in `block in synchronize'  /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:58:in `synchronize'  vendor/bundle/ruby/2.2.0/gems/redis-3.3.0/lib/redis.rb:861:in `get'  vendor/bundle/ruby/2.2.0/gems/redis-store-1.1.7/lib/redis/store/interface.rb:5:in `get'  vendor/bundle/ruby/2.2.0/gems/redis-store-1.1.7/lib/redis/store/marshalling.rb:17:in `get'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:230:in `block in read_entry'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:212:in `call'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:212:in `with'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:230:in `read_entry'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:413:in `block in exist?'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:547:in `block in instrument'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/notifications.rb:166:in `instrument'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:547:in `instrument'  vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.6/lib/active_support/cache.rb:412:in `exist?'  vendor/bundle/ruby/2.2.0/gems/redis-activesupport-4.1.5/lib/active_support/cache/redis_store.rb:200:in `exist?'  

My cache initialization code is

Rails.application.configure do      Rack::MiniProfiler.config.storage_options = { host: 'redis.local.com', port: 6379 }      Rack::MiniProfiler.config.storage = Rack::MiniProfiler::RedisStore      config.cache_store = :redis_store, http://redis.local.com:6379, { expires_in: 5.minutes }      Rails.cache = ActiveSupport::Cache::RedisStore.new  end  

Having searched all over the redis-rb and redis-store gems, hasn't turned up anything at all. How do I ensure passenger does not create multiple connections to Redis when using it as cache store?

Multisearch pg_search with Rails

Posted: 28 Jun 2016 07:29 AM PDT

I have a question about multi field search using pg_search gem. What I want to do is make a query in multiples fields, so I have the following code in my Client model:

  pg_search_scope :search,      :against => [:name, :email],      :using => [:trigram, :tsearch],      :ignoring => :accents  

For testing I have:

Client 1

name: "Anna"

email: "mycompany@foo.com"

Then I searched with Client.search("anna") and no results are returned. Or Client.search("nna") also no results found.

Any suggestion here ?

Thanks in advance.

Update 1

I set the threshold manually and it works:

  pg_search_scope :search,      :against => [:name, :email],      using: {              tsearch: {},              trigram:    {threshold:  0.1}             }  

Authenticating on two different backend servers

Posted: 28 Jun 2016 07:15 AM PDT

Due to requirement changes we need to add a node server to our already existing system. We will be using sails.js for the realtime communication part of the app and redis store for session management. But the confusion now is what is the best way to authenticate the client app/user on both servers with one login form.

Any help will be much appreciated.

Ruby on Rails: is there an ideal app directory structure in Windows

Posted: 28 Jun 2016 06:59 AM PDT

Just a quick question from a Rails learner. As I understand it, it is not necessary to place a new Rails app inside the directory where Ruby and Rails are installed. But, is there an ideal place for apps? What are experienced developers using?

I ask this, because I may have misplaced a previous app, hidden somewhere deep in a directory structure; and, strange as it might seem to most of you, I cannot find where the older app is. I have quite some problems searching in Windows 10; it is a nightmare, compared to how it was in Windows XP.

Setting default value for Rails select helper block

Posted: 28 Jun 2016 07:27 AM PDT

How can I set default value in Rails select helper block?

<div class="field">    <label>Gender</label>    <%= f.select :gender, [], { prompt: 'Select gender', selected: 'Female' }, { :class => 'ui selection dropdown' } do %>      <% Subject.genders.keys.each do |c| %>        <%= content_tag(:option, value: c, class: 'item') do %>          <%= content_tag(:i, '', class: "#{c.downcase} icon") %>          <%= content_tag(:span, c) %>        <% end %>      <% end %>    <% end %>  </div>  

I tried setting it with :selected option but it doesn't work.

Convert String to DateTime Ruby

Posted: 28 Jun 2016 07:27 AM PDT

I have a string "2015-11-01T10:00:00.00+08:00" extracted from json response. How can convert it to Time or DateTime?

I tried Time.new("2015-11-01T10:00:00.00+08:00") its returning 2015-01-01 00:00:00 +0530, clearly the date is changed here and time too.

Rails/AJAX cached form submission - 422 unprocessable entity

Posted: 28 Jun 2016 06:14 AM PDT

My Rails app features a public-facing form that passes user input to the controller as a stringified JSON via AJAX. The form is designed for offline use, and so every visit to the form page other than the first is served from the browser cache (using the cache manifest). I am having an issue where the form submission returns a 422 unprocessable entity error unless the browser history has been cleared before navigating to the form page... that is to say that a user can only make one form submission, all subsequent submissions are 422 unless they clear the history and return to the form to refresh the cache. Unfortunately, that's not going to fly.

I am not tremendously experienced with Rails security, but I am under the impression that this has to do with CSRF protection and the fact that, for any visit to the form page other than the first, a stale CSRF token is being passed.

My AJAX request appears like so:

$.ajax({      url: "post/submission",      type: "POST",      dataType: "json",      beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},      data: {"post" : postParameter},      success: function(response){          window.location = '/post/approval';      }  });  

At the moment, the layout page includes the <%= csrf_meta_tags %>, and I have the standard protect_from_forgery with: :exception in the application controller.

The final structural element to note about this form is that, although the form itself is public-facing, it requires a user login after the submit button is clicked - so a submission will not be successful without a valid login.

Is there a safe way that I can get around this problem? I'm sure it goes without saying, but I can't have my users clearing their history and re-caching the form after every submission.

Rails, rollback on trying to create an instance of a model with multiple belongs_to

Posted: 28 Jun 2016 06:13 AM PDT

I have a class "Localization". "Articles" have many localizations. This worked perfectly until I created a model Event and tried to add localizations to that too.

My localization class

class Localization < ApplicationRecord      belongs_to :event      belongs_to :article      belongs_to :language  end  

My article class

class Article < ApplicationRecord      has_many :localizations, dependent: :destroy      mount_uploader :image, ImageUploader      enum article_type: [:news, :catalog, :notifs]  end  

My event class

 class Event < ApplicationRecord      has_many :localizations, dependent: :destroy      mount_uploader :image, ImageUploader  end  

My localizations table creation

create_table :localizations do |t|        t.integer :article_id        t.integer :event_id        t.integer :language_id        t.string :title        t.text :text        t.timestamps      end  

When I try to create an item of either Article or Event I get a rollback:

SQL (1.3ms)  INSERT INTO "articles" ("created_at", "updated_at", "article_type") VALUES ($1, $2, $3) RETURNING "id"  [["created_at", 2016-06-28 13:08:36 UTC], ["updated_at", 2016-06-28 13:08:36 UTC], ["article_type", 0]]     (11.5ms)  COMMIT    Localization Load (0.8ms)  SELECT  "localizations".* FROM "localizations" WHERE "localizations"."article_id" = $1 AND "localizations"."language_id" = $2 LIMIT $3  [["article_id", 4], ["language_id", 1], ["LIMIT", 1]]     (0.2ms)  BEGIN    Language Load (0.3ms)  SELECT  "languages".* FROM "languages" WHERE "languages"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]     (0.3ms)  ROLLBACK  

What am I doing wrong?

How to import a postgis db on heroku with rails

Posted: 28 Jun 2016 06:11 AM PDT

How to correctly import a postgres 9.4 + postgis 2.1 database on Heroku with rails ?

They have beta support for postgis, however I tried using pg:push as they documented, but it throws a warning about needing to be a sudo user to create postgres operators.

Moreover I can't be sure the complex data I have (multipolygons) is correctly copied during the process. Is there a specific process to follow for postgis ?

Thanks.

How to keep same order on each session?

Posted: 28 Jun 2016 06:15 AM PDT

I'm working on a store in rails. As I'm new to Rails I was following some tutorial on how to create a shopping cart and ordering system.

So right now orders with unique ids are being created and saved by a user, automatically, upon addition of a order_item to a cart on each new session. And this is the issue.

I want order to persist until 30 days passes (the one order that is created first, that is, when first order_item has been added by a user). The problem is next: So if user adds order_items, he creates an order and then logs out and comes back and adds a new order_item to his cart, new order is being created even though there is already his older order saved to database. I want to retrieve that first order.

Can you please tell me how to achieve this?

class OrderItemsController < ApplicationController    def create      @order = current_order      @order_item = @order.order_items.new(order_item_params)      @order.user_id = current_user.id      @order.save      session[:order_id] = @order.id      respond_to do |format|      format.js { flash[:notice] = "ORDER ITEM HAS BEEN ADDED." }     end    end  

order_item.rb

class OrderItem < ActiveRecord::Base    belongs_to :product    belongs_to :order    validates_associated :order    validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }    validate :product_present    validate :order_present        before_save :finalize      def unit_price      if persisted?        self[:unit_price]      else        product.price      end    end      def total_price      unit_price * quantity    end    private    def product_present      if product.nil?        errors.add(:product, "is not valid or is not active.")      end    end      def order_present      if order.nil?        errors.add(:order, "is not a valid order.")      end    end      def finalize      self[:unit_price] = unit_price      self[:total_price] = quantity * self[:unit_price]    end      end  

order.rb

class Order < ActiveRecord::Base    belongs_to :order_status    belongs_to :user    has_many :order_items    validates_length_of :order_items, maximum: 3    before_create :set_order_status    before_save :update_subtotal          def subtotal      order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum    end  private    def set_order_status      self.order_status_id = 1    end      def update_subtotal      self[:subtotal] = subtotal    end        end  

user.rb

has_many :order  

Initialize Ruby codes error

Posted: 28 Jun 2016 06:33 AM PDT

I tried to run these codes:

class Dog         def set_name(name)        @dogname = name     end       def get_name        return @dogname     end       def talk        return "awww"     end       def initialize(title, description)        @title = title        @description = description     end      end    doggy = Dog.new  doggy.set_name('Sam')  puts doggy.get_name  puts doggy.talk      bogart = Dog.new('The Book', 'The road not taken')  puts bogart.to_s  puts bogart.inspect  

I did make sure every argument is correct. However, I got the following errors.

C:\Ruby200\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/Users/Todd/RubymineProjects/untitled1/test.rb  C:/Users/Todd/RubymineProjects/untitled1/test.rb:15:in `initialize': wrong number of arguments (0 for 2) (ArgumentError)      from C:/Users/Todd/RubymineProjects/untitled1/test.rb:22:in `new'      from C:/Users/Todd/RubymineProjects/untitled1/test.rb:22:in `<top (required)>'      from -e:1:in `load'      from -e:1:in `<main>'    Process finished with exit code 1  

Tried my best can't find the issue. Any idea where I miss?

Webmock stub request not working

Posted: 28 Jun 2016 06:16 AM PDT

I need to make a request to facebook throw an error, so that I can ensure my circuit breaker is working.

My test is this

context 'when Facebook API is not responding' do    before(:each) do      stub_request(:get, 'facebook.com/*')        .with(headers: { 'Accept' => '*/*', 'Content-Type' => 'application/json', 'User-Agent' => 'Faraday v0.9.2' })        .to_raise(StandardError)    end      it 'should return error code 40' do      3.times { post :create, valid_params }      expect(Oj.load(response.body)['code']).to be_eql '40'    end      it 'message should say that Facebook is not answering' do      3.times { post :create, valid_params }      expect(Oj.load(response.body)['error']) =~ 'not answering'    end  end  

If I configure VCR like this:

c.allow_http_connections_when_no_cassette = true  

the tests does not pass, and I see even with the stub_request, the app calls Facebook endpoints.

If I change allow_http_connections_when_no_cassette to false, it throws an error and trips my circuit breaker

Switching facebook_user_data from green to red because VCR::Errors::UnhandledHTTPRequestError

Although with the circuit tripped the tests pass, it is not the correct exception thrown.

Testing Angular CoffeeScript with vanilla JS?

Posted: 28 Jun 2016 05:03 AM PDT

I'm about to inherit a somewhat mature Rails monolith for work. The previous maintainers chose to write Angular JS controllers and whatnot in CoffeeScript, served through the Rails asset pipeline. I prefer regular old JS because I hate having to 'translate' documentation just to hope that it compiles to the right JS.

I also lack tests. No mocha, no jasmine, no capybara, nada.

Before I jump in and start converting the Coffee to JS file by file, I would like some tests so I know that my preference for JavaScript doesn't completely wreck everything. Does anyone have experience writing tests for Coffee-Angular in vanilla JS?

Show Results Based on experiment_type

Posted: 28 Jun 2016 07:24 AM PDT

I have a table experiments in my database that is populated by filling out a form. One of the fields in the form is experiment_type, which is a drop down option to select between either AOV or Conversion. In my show.html.erb I'd like to display the AOV experiments and the Conversion experiments seperately. I'm kinda stuck on where to begin with this. I thought I could do something in my show action like

@aov_experiment = Experiment.where(:experiment_type => "AOV").order("created_at DESC")    @conversion_experiment = Experiment.where(:experiment_type => "Conversion").order("created_at DESC")  

Then loop through and show the results in my show.html.erb

I think I am way off here. Hoping someone can point me in the right direction.

Can I find the key an embedded document is embedded under in MongoMapper?

Posted: 28 Jun 2016 04:53 AM PDT

Say I have a document like this:

{    one: {name: "John"},    two: {name: "Paul"},    three: {name: "George"},    four: {name: "Ringo"}  }  

I've ended up with the three subdocument as a MongoMapper object. I know I can find the parent document, I can read the name attrib on the object I have, but is there an easy way to find the fact that it's embedded as three in the parent document?

I have two potential solutions, but both strike me as flaky. One is to get the class name of the object (which I'd then have to mess with since these classes are all subclasses of another class) and another would be some sort of match on all the embedded documents in the parent (which seems very non-optimal).

getting latitude and longitude values from controller in rails-geocoder gem

Posted: 28 Jun 2016 05:03 AM PDT

Is it possible to get latitude and longitude values in the controller when using geocoder gem in rails?

What am currently doing for getting all nearby location is pass the location name like below.

event_address = Event.near(location, 15, order: 'distance')  

So is there a way to fetch the lat and lng which was used for the above requested location for using later in subsequent requests for same location?

@latitude= #some method

@longitude= #some_method

Migration for changing belongs_to association

Posted: 28 Jun 2016 05:14 AM PDT

I have a model called categories currently they belong to product but I'd like them to belong to store instead. I have several thousand of these so what I'd like to do is create a migration that adds a store_id to categories and then, gets the associated product.store.id from it's current association and adds that to the store_id. After that I'd like to remove the product association.

Does anybody know how to easily and safely achieve that?

delete dash character which is at the end of the string

Posted: 28 Jun 2016 05:13 AM PDT

So I have table items in my db. I want in Item.name replace - character which is at the end of the Item.name So I try to do it like this:

 items = Item.all   items.each do |it|   it.name=it.name.gsub('/\-$/','')   it.save   end  

But it doesn't work. What do I do?

upd: I managed to do it like this:

i = Item.all   i.each do |it|   it.name=it.name.chomp('-')   it.save   end  

But still don't get why first variant didn't work

Correct s3 region not setting with paperclip

Posted: 28 Jun 2016 04:55 AM PDT

Using these two gems, I had no issues:

gem 'aws-sdk', '< 2.0'  gem "paperclip", "~> 4.3"  

When now using:

gem "paperclip", "~> 5.0.0.beta1"  gem 'aws-sdk', '>= 2.0.34'  

I have region issues in development.rb:

  config.paperclip_defaults = {         :s3_region => ENV['S3_REGION'], # us-west-2         :storage => :s3,         :s3_credentials => {         :bucket => ENV['S3_BUCKET_NAME'],         :access_key_id => ENV['AMAZON_ACCESS_KEY_ID'],         :secret_access_key => ENV['AMAZON_SECRET_ACCESS_KEY']    }  }  

I see no documentation on this. The url I'm after is https://s3-us-west-2.amazonaws.com<bucken-name>.... but I'm getting: https://s3.amazonaws.com/...

Parse Postgres date stored as string including offset timezone

Posted: 28 Jun 2016 07:07 AM PDT

I have some dates stored as strings in a postgresdb

"Fri, 24 Jun 2016 04:13:26 -0700"  

I want to treat those dates as dates.

I can use

to_timestamp(date,'Dy, DD Mon YYYY HH24:MI:SS')  

But I can't work out how to deal with the timezone. there appears to be OF as the parameter for the offset.

If I use

to_timestamp(date, 'Dy, DD Mon YYYY HH24:MI:SS OF')  

The query hangs. I can't work out what I'm doing wrong there.

Note: I'm using activerecord and rails. so the query is actually

Model.all.order("to_timestamp(date,'Dy, DD Mon YYYY HH24:MI:SS OF') DESC")  

Monday, June 27, 2016

How to restrict order creation | Fixed issues

How to restrict order creation | Fixed issues


How to restrict order creation

Posted: 27 Jun 2016 08:11 AM PDT

So in my rails app I have store with products, order_items, orders, user, cart... Right now, orders are being created and saved in database upon new session for a user. So if user adds 1 order_item to his order, logs out, comes back again and ads a new order_item, new order is being created in database. The old order for that 1 order_item still exist in database however it's not being showed for a current_user on the frontend, because new order is created.

What I want to achieve is that there should be only one order per 30 days per user. So even if user adds some order_items, logs out, come back again, to have that existing order associated with that user as well on the frontend. And it should be like that for 30 days... Counter for new order should start upon addition of the first order_item.

To sum up: So I want not to create new orders upon new session for current_user, instead to show the order that has be created from previous session and keep it like that for 30 days...

How can I achieve this?

class OrderItemsController < ApplicationController   def create      now = Date.today    if current_user.begin_date && ((now - 30) < current_user.begin_date)       if current_user.order_counter >= 3          redirect_to root_path       else         current_user.order_counter += 1         current_user.save       end    else       current_user.order_counter = 1      current_user.begin_date = now      current_user.save    end    @order = current_order    @order_item = @order.order_items.new(order_item_params)    @order.user_id = current_user.id    @order.save    session[:order_id] = @order.id      respond_to do |format|      format.js { flash[:notice] = "ORDER HAS BEEN CREATED." }     end  end    private      def order_item_params      params.require(:order_item).permit(:quantity, :product_id, :user_id)     end  end  

order_item.rb

class OrderItem < ActiveRecord::Base    belongs_to :product    belongs_to :order    validates_associated :order    validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }    validate :product_present    validate :order_present        before_save :finalize      def unit_price      if persisted?        self[:unit_price]      else        product.price      end    end      def total_price      unit_price * quantity    end    private    def product_present      if product.nil?        errors.add(:product, "is not valid or is not active.")      end    end      def order_present      if order.nil?        errors.add(:order, "is not a valid order.")      end    end      def finalize      self[:unit_price] = unit_price      self[:total_price] = quantity * self[:unit_price]    end      end  

order.rb

class Order < ActiveRecord::Base    belongs_to :order_status    belongs_to :user    has_many :order_items    validates_length_of :order_items, maximum: 3    before_create :set_order_status    before_save :update_subtotal      def subtotal      order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum    end  private    def set_order_status      self.order_status_id = 1    end      def update_subtotal      self[:subtotal] = subtotal    end  end  

cart_controller.rb

class CartsController < ApplicationController    def show      @order_items = current_order.order_items    end      end  

Bundler is using a binstub that was created for a different gem - in the context of a Rails engine

Posted: 27 Jun 2016 08:03 AM PDT

I have created a simple Rails engine, using Rails v4.2.6. Now it ran into problems related to the "binstub management":

When I invoke the rails binary/binstub, e.g. via rails -v or when I navigate to the dummy application within spec/dummy and I want to start a rails console, I get the following warning:

Bundler is using a binstub that was created for a different gem.  This is deprecated, in future versions you may need to `bundle binstub my-sample-engine` to work around a system/bundle conflict.  

And if I use my engine within another Rails application, this error message is propagated to the hosting application - I get the same message when starting a rails console session there. The warning remains even when I invoke the console via bundle exec rails c.

I found some suggestions in the answers of this Stackoverflow discussion but unfortunately the suggestions did not resolve the problem in my situation.

What I have tried so far:

  1. Deleting the "top-level binstub" located in bin/. There ony was a single binstub for rails. But, no success. If I run "rails -v" afterwards the warning appears again

  2. Deleting/re-creating the binstubs within the dummy application via rm -rf bin/ && rake rails:update:bin was not successful, too.

  3. Configuring bundler to turn off its binstub generator by bundle config --delete bin and repeating 1 and 2 did not help, too.

What went wrong in my case? How can I fix the "wrong" binstub situation?

Hopefully useful trivia: I'm using bundler version 1.11.2, rails version 4.2.6 and as stated above, everything happens within a mountable engine.

Override javascript_tag type for json-ld in Rails 3.2.x

Posted: 27 Jun 2016 07:52 AM PDT

Looking at the underlying code for javascript_tag it may not be possible, but does anyone know if it's possible to override the javascript_tag default type of type="text/javascript" in Rails 3.2.2? Or possible without a lot of janky code?

I'm trying to do something like this, but I can look into other options.

javascript_tag type: 'application/ld+json' do      some stuff here  end  

Ruby-on-Rails: Can enum value be a string. Where is this documented?

Posted: 27 Jun 2016 07:49 AM PDT

Can someone point me to some ROR documentation that describes setting the value of an enum as a string? All the documentation and examples I've found seem to indicate that the value should be an integer. However I am able to create an enum with string values, use it in view and save it to the database without any issues. I would really like to find out more on this topic.

Example that works

Set in ModelName

enum category_enum: { 'abc efg'=> 'alpha', 'hot dog' => 'bun' }  

Set in view

<%= f.select :category, ModelName.category_enums %>  

Rails. Search MongoDB field that is an array of arrays

Posted: 27 Jun 2016 07:49 AM PDT

I'm writing my own RoR based archive app for email and have a field named headers which is an array of arrays. The first element of each sub-array is the header name and the second is the header value. I'd like to be able to search for headers of certain types, i.e.."Received', 'X-Spam-Status', etc. and/or the contents of a header, i.e. 'from mail.apache.org', 'score=-4.7', etc. I've tried .where(headers: {'$in' => [['Received']]}) and many variations with no luck. Can anyone help me out? Thx. in advance.

How to add and remove a class to hide and show a table row?

Posted: 27 Jun 2016 07:46 AM PDT

In my current situation in my Ruby on Rails application, I am trying to make a drop-down function on each table tow to show advanced details for a server that comes from a database. My through process is to make the hidden row default to display: none; then add a viewing class when it is clicked to view it, then hide it when it is clicked again. Here is my javascript:

var hideDetails, showDetails;  showDetails = function() {    $(this).closest('tbody').addClass('viewing');    return false;  };  hideDetails = function() {    $(this).closest('tbody').removeClass('viewing');    return false;  };      $table.on('click', 'tbody.viewing', hideDetails);  $table.on('click', '.details-link', showDetails);  

Then my css:

table.collapsible {      // css for drop-down      #hiddenRow.details {        display: none;        tbody.viewing {            #hiddenRow.details {              display: table-row;            }        }      }    }  

Lastly, my HTML code:

<table id="servertable" class="paginated table collapsible table-hover sortable"     data-sort-name="name" data-sort-order="desc">    <tr style="background-color: #cccccc">      <th><%= sortable "pod_id" %></th>      <th><%= sortable "ip"%></th>      <th><%= sortable "status"%></th>      <th><%= sortable "datacenter"%></th>      <th><%= sortable "memory_used"%></th>      <th></th>    </tr>    <!--A for loop to iterate through the database and put it into the table-->    <tbody>      <% @servers.each_with_index do |server| %>        <tr>           <td><%= server.pod_id %></td>          <td><%= server.ip %></td>          <td><%= server.status %></td>          <td><%= server.datacenter %></td>          <td><%= (server.memory_used * 100).floor %>%</td>          <td><input type="button" onclick="showDetails(); hideDetails();"></input></td>          <tr id="hiddenRow">            <td colspan="6">Information</td>          </tr>        </tr>      <% end %>    </tbody>  </table>  

My problem is that even though in my css, I have the default display of the hidden row to be none, it is still showing up on the screen. As well as the button not functioning as well. Some help would be appreciated.

Note: There is some extra stuff in my HTML code because I have some other functions for my table such us sortable columns, just ignore that, it doesn't have to do with my question.

Having a Ruby on Rails Selector without a form

Posted: 27 Jun 2016 07:42 AM PDT

I have a schools' program table set up, and want a user to be able to add a new program to a school. The new school program path requires a school passed to it to denote which school is getting a new program. In the first scenario, there is already a school selected and so a new program can be added to that school. In the second scenario however, there is no school selected yet. I was wondering how to add a dropdown that has all of the schools available so that someone can choose which school they want to add a program in - but I am trying to do so without a form.

<% if @school %>      <% if can? :create, @program %>        <%= link_to 'New Program', new_school_program_path(@school), class: 'btn btn-primary' %>        <br/>      <% end %>  <% else %>    <% if can? :create, @program %>      <%= select @selected_school, [School.all]%>      <%= link_to 'New Program', new_school_program_path(@selected_school), class: 'btn btn-        primary' %>      <br/>    <% end %>  <% end %>

Prevent Google crawling other folders in /var/www/

Posted: 27 Jun 2016 07:57 AM PDT

We have a website build on Ruby on Rails reverse proxied with Apache. So the root folder for the website would be /var/www/html/digiryte and the folder structure is similar to this

/var/www/html/      rails_website/      folder1/      folder2/      index.html  

The trouble is google's webmaster console is showing crawl errors with the url like

/html/rails_website/public/assets/...  

How is this possible?
How can I stop google from indexing those folders?

Rails application to not redirect to HTTPS on specific controller and action

Posted: 27 Jun 2016 07:43 AM PDT

How can my application not redirect to HTTPS on a certain controller and action ? In my case it's the controller transaction and action update_payment. I'm having loop redirect problem on production.

I've tried using the the gem rack-ssl-enforcer and putting the following in the production.rb:

config.middleware.use Rack::SslEnforcer, :except => [%r{update_payment$}], :strict => true  

Still, it seems it's not working..

rake aborted! cannot load such file Ruby on Rails

Posted: 27 Jun 2016 07:32 AM PDT

I am trying to run a ruby file that updates the database using the rake task . But overtime I run the code, I get an error saying : rake aborted! cannot load such file -- app/services/insert_data

The ruby file 'insert_data' is located under the app directory in a folder named 'services'

Here is the rake task I created to run it:

require 'app/services/insert_data'    namespace :record_generate do      task :test do    ruby "app/services/insert_data"  end      end  

Please help in removing this error.

Ruby Retrieving from Array

Posted: 27 Jun 2016 07:22 AM PDT

So i get an array of hashes like this

[1, {"item_name"=>"Estella Top", "item_number"=>"73", "quantity"=>"1", "option_name1_"=>"UK - 4, White"}]    [2, {"item_name"=>"Test Top", "item_number"=>"74", "quantity"=>"1", "option_name1_"=>"UK - 4, Red"}]  

I have this create action:

def create  f_turn = extract_items    Page.create!(line_item_id: "#{f_turn.fetch("item_number")}",   option_name: "#{f_turn.fetch("option_name1_")}", quantity: "#{f_turn.fetch("quantity")}")   render nothing: true  end  

extract items is a function that extracts the array.

I need those values, but for some reason, its not working.

I've also tried:

def create  f_turn = extract_items    f_turn.each do |key, values|    Page.create!(line_item_id: ["item_number"],   option_name: ["option_name1_"], quantity: "["quantity"])   render nothing: true  end  

None of them work. With the latter, instead of the actual value, i get "[\"item_number\"]" as the value. Any help would be appreciated! Thanks in advance!

UPDATE Mistakes in the code

def extract_items    mod_params = Hash.new{|k, v| k[v] = {} }      ITEM_PARAM_PREFIXES.each do |item_data_key|        key_tracker = 1        loop do            current_key = (item_data_key + key_tracker.to_s).to_sym            if params.include? current_key                mod_params[key_tracker][item_data_key] = params[current_key]            else                break            end            key_tracker += 1        end    end    mod_params  end  

Using database entries to populate checkbox data ruby rails

Posted: 27 Jun 2016 07:06 AM PDT

I'm trying to create a page with a series of checkboxes on it for which the text associated with them will be pulled from a database. The view on which the form should be is named keyword_search and is located within the searches folder. The below is the code I've used to try and create the checkboxes in the view:

 <% @topic.each do |degree| %>  <form action="recommender_results.html.erb" method="get">    <input type="checkbox" name="topic" value="topic"><%= recommend.topic %><br>  </form>  

And below is the code I have within the searches contrller:

def new  @topic = Recommend.new  end    def keyword_search  @topic = Recommend.all.select(:topic)  end  

Can I Populate / update a new record after using find_or_initialize_by with one line like when using new()?

Posted: 27 Jun 2016 07:41 AM PDT

I am in the process of changing some functionality and as such, I want to use find_or_initialize_by to replace new

My modal has 13 columns

modal = Modal.new(col1: col1, col2: col2..... col13: col13)  

The new code is:

modal = Modal.find_or_initialize_by(col1: col1, col3: col3)  

and now I need to either populate or update the remaining 11 columns.

Can this be done on one line? I would rather not write:

modal.col1 = col1  modal.col2 = col2  ....  modal.col13 = col13  

Thanks

Multiple urls with Paperclip

Posted: 27 Jun 2016 06:59 AM PDT

Is it possible to upload multiple files with Paperclip? I've tried my best by going through their docs but noting useful.

I want to submit an array value to a rails 5 controller using react.

My state has an array, let's say [a, b, c]. In my render, I have:

<form>    <!-- I have an input file button for the upload visible -->    <input type="hidden" name="user[image][]" value={this.state.files} />  </form>  

To make this example slimmer, I only show the hidden field where the value is. The submitted params looks "encrypted" but I'm confident I see the array.

My controller:

# :image is not permitted  params[:user][:image].each do |image |    User.find(1).update_attributes(user_params.merge({image: image}))  end   

Only the first image in the array is being saved. Does paperclip supports multiple? The aim is: User.find(1).image.url, then I'd see an array of urls.

I'm using PostgreSQL as the db so not sure if I should make the table column an array but do paperclip supports that?

How do I express i18n and devise on route.rb

Posted: 27 Jun 2016 06:46 AM PDT

I'm configuring omniauth and devise with i18n on route.rb But I can't figure out how.

scope "(:locale)", locale: /en|ja/ do     get '/' => 'frontpage#index'     get 'restaurant/' => 'restaurant#index'     get 'restaurant/:id' => 'restaurant#show'     get 'menu/' => 'menu#index'     get 'menu/:id' => 'menu#show'     get 'area/' => 'area#index'     get 'area/:id' => 'area#show'    devise_for :users, :controllers => {       :sessions       => "users/sessions",       :registrations  => "users/registrations",       :passwords      => "users/passwords",       :omniauth_callbacks => "users/omniauth_callbacks"  }  end  

Does it make sense? And could you tell me how to configure please?

capybara have_title NoMethodError

Posted: 27 Jun 2016 06:52 AM PDT

At the moment, this is a simple project - just a couple of static pages. I'm developing a generic test framework but am struggling to differentiate between the different test options. I have added Rspec, Capybara, Faker, Factory Girl, Spring, and shoulda (though I'm not using the shoulda matchers at the moment).

I have this controller test file:

require 'rails_helper'    RSpec.describe StaticPagesController, type: :controller do      describe "GET #a_page" do      before(:each) { get :a_page }        it "returns http success" do        expect(response).to have_http_status(:success)      end      it "has a page title Static Site" do         expect(response).to have_title('Static Site')       end     end    end  

When this runs through guard, it throws an error stack:

23:13:39 - INFO - Run all  23:13:39 - INFO - Running all specs  Running via Spring preloader in process 4498  Running via Spring preloader in process 4506  /home/steve/workspaces/static_site/db/schema.rb doesn't exist yet. Run `rake db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/steve/workspaces/static_site/config/application.rb to limit the frameworks that will be loaded.  .F    Failures:      1) StaticPagesController GET #a_page has a page title Static Site       Failure/Error: expect(response).to have_title('Static Site')         NoMethodError:         undefined method `match' for nil:NilClass         Did you mean?  catch       # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/queries/title_query.rb:18:in `resolves_for?'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/node/document_matchers.rb:20:in `block in assert_title'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/node/simple.rb:144:in `synchronize'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/node/document_matchers.rb:19:in `assert_title'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/rspec/matchers.rb:105:in `matches?'       # ./spec/controllers/static_pages_controller_spec.rb:34:in `block (3 levels) in <top (required)>'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/command_wrapper.rb:38:in `call'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:191:in `block in serve'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:161:in `fork'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:161:in `serve'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:131:in `block in run'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:125:in `loop'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:125:in `run'       # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application/boot.rb:19:in `<top (required)>'       # -e:1:in `<main>'    Finished in 0.029 seconds (files took 2.54 seconds to load)  2 examples, 1 failure    Failed examples:    rspec ./spec/controllers/static_pages_controller_spec.rb:33 # StaticPagesController GET #a_page has a page title Static Site  

The first test runs OK and, without the second, I get a clean result. I've spent a lot of time going over my config and it looks OK. I have also looked at the docs and some support sites.

Can anybody help out?

Using images from database with embedded ruby in bootstrap carousel

Posted: 27 Jun 2016 06:35 AM PDT

My carousel works with this:

<div class="item">    <a href="https://www.google.com" target="_blank">      <%= image_tag "happyface.jpg", class: "imgslide" %>        <div class="carousel-caption">          <p>Eating an apple a day keeps the doctors away </p>        </div>    </a>  </div>     

But does not work when I attempt this:

<div class="item">    <%= link_to(@articles.first.source, target: "_blank") do %>      <%= image_tag(@articles.first.artwork.url, class: "imgslide") %>        <div class="carousel-caption">          <%= @articles.first.title %>          </div>    <% end %>  </div>  

How do I make this work?

How to Retrieve or Change the msql password for Ruby on Rails

Posted: 27 Jun 2016 07:09 AM PDT

I am doing my very first practice on ruby on rails and everything was going fine until I tried running the server for the first time. On the command line (while in the root directory of my proyect) I typed "rails server" and when visiting localhost:3000 in the browser I get this error message: "Mysql2::Error Access denied for user 'root'@'localhost' (using password: YES)"

Per the instructions it says that I must comment out the "#database: simpe_cms_development" in the database.yml which I did.

It also says that I must provide the password that I set when installing msql. I set the password in database.yml file as "boots"

          username: root          password: boots          host: localhost         
But I still get the same error.

My problem is that I am not sure now if this is the correct password I set to begin with. What I want to know is how to retrieve that original password I set o how to set a new one. Thanks!

enter image description here

PS:

I've just opened up mysql command line client and the first thing it ask for is a password to allow access. I Typed "boots" and it did allow access to the mysql command line client. So the problem I have is NOT the pássword. :( Any Ideas on how to debug anybody?

How to catch base exception class in Ruby on Rails?

Posted: 27 Jun 2016 06:01 AM PDT

I'd like to catch any RoR exceptions in REST API application with 'rescue_from'.

rescue_from StandardError do |exception|    message = Rails.env.production? ? 'API server error' : exception.message    render json: {status: "Error", message: message}, status: :internal_server_error  end  

but it catches too much irrelevant exceptions. Can I catch RoR exceptions only? Is it a good practice at all? If not, what else you can recommend?

How to display a pie chart of all service->orders->count?

Posted: 27 Jun 2016 06:00 AM PDT

I am trying to display a pie chart displaying all the count of services by using chartkick gem : http://chartkick.com/

service has_many :orders  orders  belongs_to :service  

My db schema is here

create_table "services", force: :cascade do |t|    t.string   "name"    t.datetime "created_at",       null: false    t.datetime "updated_at",       null: false    t.integer  "priority"    t.text     "description"    t.integer  "delivery_charges"    t.integer  "min_stamp"  end    create_table "orders", force: :cascade do |t|    t.integer  "document_id"    t.integer  "user_id"    t.integer  "status_id"    t.string   "stamp_amount"    t.datetime "created_at",                           null: false    t.datetime "updated_at",                           null: false    t.integer  "service_id"    t.string   "total_amount"    t.string   "delivery_amount"    t.string   "txnid"    t.string   "invoice_url"    t.boolean  "draft_confirmed",      default: false    t.string   "soft_copy_url"    t.boolean  "draft_required",       default: true    t.integer  "delivery_status_id"    t.integer  "delivery_partner_id"    t.string   "delivery_tracking_no"    t.string   "product"    t.integer  "platform_id",          default: 1    t.integer  "address_id"    t.string   "pickup_amount"    t.boolean  "draft_created",        default: false    t.string   "draft_url"    t.text     "correction"    t.integer  "coupon_id"    t.string   "discount"    t.text     "summary",              default: ""  end  

There are several services such as affidavit, notary etc. Each service in turn have one or more document orders of type "house agreement", "bonds" etc. I want to display the order count of these different documents of each service in a pie chart. How do I achieve this. Please help. Let me know if more data is required.

Rails - how to fetch from ActiveRecord object only specific records?

Posted: 27 Jun 2016 06:21 AM PDT

I get this from an ActiveRecord call:

#<ActiveRecord::Associations::CollectionProxy [    #<CarService id: nil, car_id: nil, car_service: 1,                  created_at: nil, updated_at: nil, car_type: 0>,     #<CarService id: nil, car_id: nil, car_service: 11,                 created_at: nil, updated_at: nil, car_type: 1>]>  

Once I get this, I need to filter only records where car_type = "0". How to do that without doing another database call (WHERE car_type = "0")?

Thank you in advance.

EDIT:

this:

car.car_services.select{|key, hash| hash['car_type'] == "1" }  

does not work.

rake aborted! NoMethodError: undefined method when migrated to Rails 4.0

Posted: 27 Jun 2016 06:51 AM PDT

I am working on Rails application migration from 3.2.13 to 4.0.0, before running the application, I need to run a seed file:

seeds.rb

# This file should contain all the record creation needed to seed the database with its default values.  # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).  #  # Examples:  #  #   cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])  #   Mayor.create(:name => 'Daley', :city => cities.first)    # Create subscription plans      SubscriptionPlan.find_or_create_by_name(name: "free", amount: 0.00, renewal_period: 1, trial_period: 30, description: 'Free Plan')      SubscriptionPlan.find_or_create_by_name(name: "year", amount: 149.00, renewal_period: 12, trial_period: 30, description: "Year Plan")  

This is the table:

create_table "subscription_plans", :force => true do |t|        t.string   "name"        t.decimal  "amount",         :precision => 10, :scale => 2        t.integer  "renewal_period",                                :default => 1        t.integer  "trial_period",                                  :default => 1        t.text     "description"  end  

While running rake db:seed, this is the error I am getting an error in current version where it is fine in previous version. Error:

rake aborted! NoMethodError: undefined method `trial_interval' for

Did you mean? trial_period /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/attribute_methods.rb:436:in

method_missing' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:131:in method_missing' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validator.rb:151:in block in validate' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validator.rb:150:ineach' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validator.rb:150:in validate' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:283:in _callback_before_39' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:407:in _run__3876620741187521333__validate__callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:80:in run_callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations.rb:373:in run_validations!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations/callbacks.rb:106:in block in run_validations!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:373:in _run__3876620741187521333__validation__callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:80:in run_callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations/callbacks.rb:106:in run_validations!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations.rb:314:invalid?' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/validations.rb:70:in valid?' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/validations.rb:77:in perform_validations' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/validations.rb:51:in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/attribute_methods/dirty.rb:32:in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:270:in block (2 levels) in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:326:in block in with_transaction_returning_status' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:202:in block in transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:210:in within_new_transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:202:in transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:209:in transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:323:in with_transaction_returning_status' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:270:in block in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:281:in rollback_active_record_state!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:269:in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/protected_attributes-1.0.3/lib/active_record/mass_assignment_security/persistence.rb:46:in create' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/relation.rb:121:in block in create' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/relation.rb:270:in scoping' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/relation.rb:121:in create' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-deprecated_finders-1.0.4/lib/active_record/deprecated_finders/dynamic_matchers.rb:141:in dispatch' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/dynamic_matchers.rb:67:in find_or_create_by_name' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/dynamic_matchers.rb:20:in method_missing' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/attr_encrypted-1.2.1/lib/attr_encrypted/adapters/active_record.rb:50:in method_missing_with_attr_encrypted' /home/abc/Desktop/Proj2/db/seeds.rb:10:in <top (required)>' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in load' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in block in load' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:213:in load_dependency' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in load' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/railties-4.0.0/lib/rails/engine.rb:540:in load_seed' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/tasks/database_tasks.rb:153:in load_seed' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/railties/databases.rake:181:in block (2 levels) in ' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/rake-11.2.2/exe/rake:27:in <top (required)>' /home/abc/.rvm/gems/ruby-2.3.0@proj/bin/ruby_executable_hooks:15:in eval' /home/abc/.rvm/gems/ruby-2.3.0@proj/bin/ruby_executable_hooks:15:in `' Tasks: TOP => db:seed (See full trace by running task with --trace)

I don't know where this trial_interval came from. I have searched entire application. Please help me.

Rails rspec undefined method `receive_message' for #<RSpec::ExampleGroups::

Posted: 27 Jun 2016 05:48 AM PDT

I'm trying to mock some data inside before(:each) and get

 NoMethodError:     undefined method `receive_message' for #<RSpec::ExampleGroups::CurrencyExchange:0x007f87c652f3c8>  

my before(:each

before(:each) do    @rates = {"exchangerates"=>              {"row"=>                   [{"exchangerate"=>{"ccy"=>"EUR", "base_ccy"=>"UAH", "buy"=>"28.33917", "sale"=>"28.33917"}},                    {"exchangerate"=>{"ccy"=>"RUR", "base_ccy"=>"UAH", "buy"=>"0.38685", "sale"=>"0.38685"}},                    {"exchangerate"=>{"ccy"=>"USD", "base_ccy"=>"UAH", "buy"=>"24.88293", "sale"=>"24.88293"}},                    {"exchangerate"=>{"ccy"=>"BTC", "base_ccy"=>"USD", "buy"=>"605.3695", "sale"=>"669.0926"}}]}}   obj = double()   @request = allow(obj).to receive_message(@rates)      end  

How to fix it?

Apache configuration to access files from outside of ruby

Posted: 27 Jun 2016 05:32 AM PDT

My server configuration is as follows:

Server running apache2  Passenger is providing ruby application      I have an images folder which is outside the ruby app  

The ruby application has the following path:

/home/myuser/domains/domainname/rubyapp  

The images folder lies at

/home/myuser/images  

I added a Location and an Alias into my apache2 configuration

<Location /home/myuser/images>  PassengerEnabled off  allow from all  Require all granted  Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI  </Location>    Alias /images /home/myuser/images  

I start the ruby application with:

passenger start -p 3001 -d -e production  

Inside the images folder there is an image file asd.jpg - which i cannot display, because i get a ruby 404 error message.

I want to access the image with www.mydomain.com/images/asd.jpg

What am i doing wrong? Which configuration has to be edited (and how)?

How to skip the malformated & invalid utf-8 errors.When csv file uploading in ralis app?

Posted: 27 Jun 2016 05:30 AM PDT

I have handle more-then 5lks data.I have working with CSV & XLSX formats. When i uploading a CSV file i have ('Rails Import CSV Error: invalid byte sequence in UTF-8' and 'Malformed error') and-then i uploading a Xlsx file i have ('Roo spreadsheet uploading OLE2 signature is invalid'). Please someone help me? This my view page code...

<%=form_for[@product],:url{:controller=>"products",:action=>"import_process"} do |f| %>      <%= f.file_field :file1,:accept=>".csv"%>       <button type="submit" class="btn btn-info" onclick="return ValidateExtension()" data-qslid="l2"><i class="fa fa-cloud-upload"></i>Upload</button><br/><br/>        <%end%>  

Getting id errors when trying to delete tags

Posted: 27 Jun 2016 05:34 AM PDT

I am extremely new to ruby on rails and I was following a tutorial to set up a simple blog style website. I had implemented tags on the articles but now I'm getting errors when trying to implement the deleting of tags. I think this is where the error is coming from.

def destroy    @tag = Tag.find(params[:id])  @tag.destroy    flash.notice = "Tag '#{@tag.name}' Deleted!"    redirect_to action: "index"    end  

I think it's the line @tag = Tag.find(params[:id]) that's causing the following error:

Couldn't find Tag with 'id'=#< Tag::ActiveRecord_Relation:0x007fdd2c016ba0>

I'm stuck with this because I managed to implement the deleting of articles in this way so I'm unsure as to why this won't work.

Edit: This is the view file.

<h1>All Tags</h1>    <ul id="tags">     <% @tag.each do |tag| %>     <li>      <%= link_to tag.name, tag_path(tag) %>        <%= link_to "delete", tag_path(@tag), method: :delete, data: {confirm: "Really delete the tag?"} %>      </li>    <% end %>  </ul>  

Rails: Update data via link_to (without view)

Posted: 27 Jun 2016 06:19 AM PDT

I'd like to update the data without form.

Although there are similar questions, they don't work for me.

Update field through link_to in Rails

link_to update (without form)

What I'd like to do is to delete data as followings;

For example, delete name and address when delete link is clicked.

id | name | address | ...  12 | aaa  | bbb     | ...  

to

id | name | address | ...  12 |      |         | ...  

Although I tried some, error was displayed.(such as ActionController::RoutingError)

schema

  create_table "rooms", force: :cascade do |t|      t.string   "name"      t.text     "address"      ...  

model

schedule.rb

class Schedule < ActiveRecord::Base    belongs_to :user    has_many :rooms, inverse_of: :schedule, dependent: :destroy    accepts_nested_attributes_for :rooms, allow_destroy: true    ...  

room.rb

class Room < ActiveRecord::Base    belongs_to :schedule, inverse_of: :rooms    default_scope -> { order(day: :asc) }    ...  

view

I'd like to add the link in schedules/_schedule.html.erb It has the followings;

  ...    <% schedule.rooms.each do |room| %>    ...      <% if room.name.present? %>          <%= link_to "Delete", rooms_path(room, room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %>    ...  

I also tried another code as below, but they don't work.

   <%= link_to "Delete", rooms_path(room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %>       <%= link_to "Delete", rooms_path(room) , method: :put, params: {address: nil}, data: { confirm: "You sure?"} %>  

and so on.

routes.rb

...    resources :schedules do      resources :events    end      resources :schedules do      resources :rooms    end      resources :rooms do      resources :events    end  ...  

It would be appreciated if you could give me any suggestion.

Populate dropdown menu from csv file rails

Posted: 27 Jun 2016 05:21 AM PDT

How can you populate a drop down menu with values from a CSV file in rails 4? Can you provide an example?

Rails 4 - notifyor gem is not sending any notifications

Posted: 27 Jun 2016 05:10 AM PDT

In rails 4, I have used gem 'notifyor' for sending desktop notifications. Referred by https://github.com/ndea/notifyor. Issue is notifications are not sending and there are no errors also.

In model, I have tried with below methods separately,

notifyor only: [:update]  

and

notifyor messages: {    update: -> (model) { "My Message for model #{model.id}." }  }  

Parallel I am running redis-server. After updating the value there is no notification is sending. Please help me to solve this issue.

How to run notify_me --ssh-host some_host --ssh-port some_port --ssh-user some_user command(please explain briefly) if it necessary to use?

Adding a counter to controller. Rails 4

Posted: 27 Jun 2016 05:33 AM PDT

I have a rails 4 app. In the controller, I iterate through each assignment entry in the database to check if a requirement is associated with more than one assignment. However, I can't figure out how to add a counter, i.e. hit = 0, hit = 1, etc. to the controller.

EDIT: The relationship between assignment and requirement is HABTM.

My code is below:

def check_requirements   @assignments = Assignment.all   @assignment = Assignment.find(params[:id])   @requirement = Requirement.find(params[:requirement_id])   @assignments.each do |assignment|        if assignment.include(requirement)          #here's where the counter should go        end    end    if counter is greater than zero or one, do nothing    else @assignment.delete(requirement)  end