vendredi 5 janvier 2018

Is there a way to optimize this scope further?

I have this chained scope that produces the following sql. It important that it be ordered created_at desc and by comments with an actual comment, and the null values after that.

It's been optimized to use subqueries instead of joins and that has helped quite a bit, but still not enough.

Ultimately, the bottleneck is with trying to get null values at the end of the results.

This is a mysql db.

I have an index on comment and created_at together

SELECT `table_one`.*
FROM `table_one`
WHERE `table_one`.`status` = 'A'
  AND `table_one`.`table_two_id` IN
    (SELECT `table_two`.`id`
     FROM `table_two`
     WHERE `table_two`.`slug` IS NOT NULL
       AND `table_two`.`status` = 'R')
  AND `table_one`.`table_three_id` IN
    (SELECT `table_three`.`table_three_id`
     FROM `table_three`
     WHERE `table_three`.`status` = 'A'
       AND `table_three`.`table_four_id` IN
         (SELECT `table_four`.`id`
          FROM `table_four`
          WHERE `table_four`.`status` = 'A'
            AND `table_four`.`table_three_id` = 6))
ORDER BY CASE
             WHEN COMMENT IS NULL THEN 1
             ELSE 0
         END,
         table_one.created_at DESC
LIMIT 20
OFFSET 0

this is querying over a million rows and will take ~12 seconds. If I remove any attempt to get the NULLS last it will run reasonably quickly.

Can you see a wat to speed it up?

Rails add @ symbol on username after Signup

Is there a gem to add the @ symbol on username after create the user?

Or this is just a html data on the websites like twitter?

jeudi 4 janvier 2018

Ruby on Rails Rollback except a given model

I am running on Rails 3.2.22 and I can't get transaction/rollback working. This code should always print "WORLD" but actually, it will never work if raise is called. But according to Rails doc, it should always reach there. My question is - is there a way how to save @pb status into a database? If I decide to save the status before rollback, it will not save. If I save it after raise, it will not execute. Is there a way around that?

    @pb = ProgressBar.create(..)
    ..
    def import(user)
    Thread.new do
      ActiveRecord::Base.transaction do
        errs = operation(user)
        Rails.logger.info "HELLO"
        if errs.any?
          raise ActiveRecord::Rollback
        end
      end
      Rails.logger.info "WORLD"
      @pb.failed_import
    end
  end

mercredi 3 janvier 2018

Rails, Devise Pending Migrations Error

I tried installing devise for rails and it works fine on heroku but when I try to run my code on my local host for my dev environment I get this error saying "Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development"

I also get these errors when I try to migrate, C:\Sites\coolguygear>bundle exec rake db:migrate == 20180103100327 AddDeviseToUsers: migrating ================================= -- change_table(:users) rake aborted! StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:7:in block in up' C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:5:inup'

Caused by: ActiveRecord::StatementInvalid: SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:7:in block in up' C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:5:inup'

Caused by: SQLite3::SQLException: duplicate column name: email C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:7:in block in up' C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:5:inup' Tasks: TOP => db:migrate (See full trace by running task with --trace)

      # Raises <tt>ActiveRecord::PendingMigrationError</tt> error if any migrations are pending.
  def check_pending!(connection = Base.connection)
    raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
  end

  def load_schema_if_pending!

mardi 2 janvier 2018

Rails listener for expired date

Is there such a thing as a listener in Ruby, or something similar? On example, how can I check if user date is expired and need to send email few days before?


Thanks on your time

Should I use hashes or ActiveRecord::Relations?

I'm really lacking some knowledge regarding efficiency/performance when working with massive amount of data.

I need to do some calculations on different models and then updating them. I was thinking:

Step I. Get the data from each table in hashes (hash_table_1, hash_table_2 etc) "plucking" the active record relations and then map it in a hash

Step II. Do calculations and change the values in the hashes (iterate over hashes, searching ids in hashes)

Step III. Updating data with Table_1.update(hash_table_1), Table_2.update(hash_table_2) etc. OR use raw SQL to update

Should I be using ActiveRecord::Relations instead of hashes? Are they more memory efficient?

lundi 1 janvier 2018

Rails 3.2.16 has_many collection build failure

Have a legacy application in Rails 3.2.16 which evaluating for an upgrade and have found an issue when running tests related to an ActiveRecord association between two models. The problem is that the when attempting to construct the associated collection it fails.

I've tested the same scenario is a simple test app using the Ruby on Rails Getting Started Guide which works (details below). The one difference between my test app and the legacy app is that the legacy app models have a number of validations on them.

The models are as follows (extra details removed for ease of reading):

class Schedule < ActiveRecord::Base
    has_many :bookings
    ...
end

class Booking
   belongs_to :schedule
   validate :ensure_sufficient_capacity
   ...
end

The bookings_controller for the new action has the following sequence:

class BookingController < ApplicationController

  def new
      #find the named schedule
      @schedule = Schedule.find_by_name("myschedule")

      #build the booking
      @booking = @schedule.bookings.build(:name => "mybooking",...)

      @booking.save #fails to save
  end

end

Some observations:

  1. The booking model has a validation on it which does a check onto a referenced schedule (the other side of the relation. Can failure on the validation cause a break in the association build ?

  2. Creating a test app as per the Rails Guides Post-Comments getting started example works with a sample of the output below shows that the has_many build operation works.

local> p = Post.new(:title => "foo")

local> #

local> p.save

local> INSERT into "posts" ("title") VALUES ($1) RETURNING "id" [["title", "foo"]]

local> c = p.comments.build(:commenter => "bar")

local> #

local> c.save

local> INSERT INTO "comments" .......