MySQL: How to create columns like "bigint" or "longtext" in Rails migrations, and what :limit means for column migrations
Rails understands a :limit
options when you create columns in a migration. Its meaning depends on the column type, and sometimes the supplied value.
The documentation states that :limit
sets the column length to the number of characters for string
and text
columns, and to the number of bytes for binary
and integer
columns.
Using it
This is nice since you may want a bigint
column to store really long numbers in it. You can just create it by ...
How to copy your „Google Chrome“ or „Chromium“ profile without creating an online account
Google Chrome saves your profile data in ~/.config/google-chrome
.
To transfer the profile to for example a system you have setup freshly do following steps:
- make a copy of
~/.config/google-chrome
- install google-chrome
- restore your backuped profile to
~/.config/google-chrome
- launch google-chrome
(Replace google-chrome by chromium-browser if you use chromium-browser)
ActiveRecord: count vs size vs length on associations
TL;DR: You should generally use #size
to count associated records.
size
- Counts already loaded elements
- If the association is not loaded, falls back to a
COUNT
query
count
- If a counter cache is set up, returns the cached value
- Issues a
COUNT
query else
Caveats
- If you trigger a
COUNT
query for an association of an an unsaved record, Rails will try to load all children where the foreign keyIS NULL
. This is not what you want. To prevent this behavior, you can useunsaved_record.association.to_a.size
. - `c...
Loading dumps via SSH, unpacking and sourcing them, all with a progress bar
Here is a hacky way to load dumps directly from the source server, without fully copying them over and extracting them first.
It may break horribly for you. This is the dark side of the force.
- Install pipe viewer, if you don't have it already:
sudo apt-get install pv
- Know the location of the dump file on the remote server. We'll use
/mnt/dumps/my_project.dump.bz2
in the example below. - Find out the size of the (bzipped) file in by...
MySQL will not use indexes if you query the wrong data type
When MySQL refuses to use your index, there's a number of things that you may be doing wrong. One of them might be conditions with improper data types.
An example
For example, let's assume you have a users
table with an email
field (varchar
) which is indexed.
MySQL will use the index when your query is well-formed:
mysql> EXPLAIN SELECT * FROM users WHERE email = 'foo@example.com';
+----+-------------+-------+-------+----------------------+----------------------+---------+-------+------+-------+
| id | select_type |...
Capturing signatures on a touch device
If you need to capture signatures on an IPad or similar device, you can use Thomas J Bradley's excellent Signature Pad plugin for jQuery.
To implement, just follow the steps on the Github page.
The form
If you have a model Signature
with name: string, signature: text
, you can use it with regular rails form like this:
- form_for @signature, :html => { :class => 'signature_form' } do |form|
%dl
%dt
= form...
Rails SQL Injection Examples
This page lists many query methods and options in ActiveRecord which do not sanitize raw SQL arguments and are not intended to be called with unsafe user input. Careless use of these methods can open up code to SQL Injection exploits. The examples here do not include SQL injection from known CVEs and are not vulnerabilites themselves, only potential misuses of the methods.
Please use this list as a guide of what not to do.
Edge Rider: Power tools for ActiveRecord scopes
In our continued quest to extract proven code snippets from makandropedia into tested and upgradable gems, we have released Edge Rider.
Edge Rider was created with two intents:
- Provides a number of utility methods to facilitate hardcore work with scopes.
- Provide a stable API for working with scopes across multiple versions of Rails, since Rails has a tradition of breaking details of its scope API every other release.
The gem bundles multiple patches and initializers we've been using for hard...
Traverse an ActiveRecord relation along an association
The Edge Rider gem gives your relations a method #traverse_association
which
returns a new relation by "pivoting" around a named association.
Say we have a Post
model and each Post
belongs to an author:
class Post < ActiveRecord::Base
belongs_to :author
end
To turn a relation of posts into a relation of its authors:
posts = Post.where(:archived => false)
authors = posts.traverse_association(:author)
You can traverse multiple associations in a single call.
E....
The many gotchas of Ruby class variables
TLDR: Ruby class variables (@@foo
) are dangerous in many ways. You should avoid them at all cost. See bottom of this card for alternatives.
Class variables are shared between a class hierarchy
When you declare a class variable, it is shared between this and all descending (inheriting) classes. This is rarely what you want.
Class variables are bound at compile-time
Like unqualified constants, class variables are bound to your current scope *whe...
Allow setting the #id attribute when creating an ActiveRecord
When creating an ActiveRecord with .new
, .create
or create!
, you cannot set the ID attribute (note: When using Machinist's .make
you can).
This is because even when you are not using attr_protected
or attr_accessible
, some attributes are always protected. These attributes are #id
and #type
.
If you want to allow setting #id
on .new
, .create
or create!
you can include the attached module in order to whitelist #id
on a model of your choice like this:
class MyModel <...
ActiveRecord 2.3: Nested attribute changes disappear
There is a bug in ActiveRecord 2.3.x that leads to changes in nested forms getting lost.
class Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks
end
If you access project.tasks
after setting tasks through the nested attribute logic, all tasks will be reloaded and all changes will be lost. This usually happens
- in validations
- in callbacks
- after validation errors, when rendering the view again
The attached initializer fixes those issues.
High Performance Networking in Google Chrome
About Chrome's network stack and optimizations to load web pages faster.
Regex: Be careful when trying to match the start and/or end of a text
Ruby has two different ways to match the start and the end of a text:
-
^
(Start of line) and$
(End of line) -
\A
(Start of string) and\z
(End of string)
Most often you want to use \A and \z.
Here is a short example in which we want to validate the content type of a file attachment. Normally we would not expect content_type_1
to be a valid content type with the used regular expression image\/(jpeg|png)
. But as ^
and $
will match lines, it matches both content_type_1
and content_type_2
. Using \A
and \z
will wo...
Pitfall: ResourceController overwrites where ActiveRecord enqueues
Defining one callback several times in the same class behaves different in ActiveRecord and ResourceController.
While in ActiveRecord the callbacks are enqueued, they overwrite each other in ResourceController.
ActiveRecord - a common practice
class Post < ActiveRecord::Base
does 'post/behavior'
before_validation :do_something
end
module Post::BehaviorTrait
as_trait do
before_validation :do_something_else
end
end
do_something_else
and do_something
are executed before validation in exactly this order
ResourceC...
Consul: Querying a power that might be nil
Consul 0.6.1+ gives your Power
class a number of static methods that behave neutrally in case Power.current
is nil
. This allows you to create authorization-aware models that still work when there is no user at the end of a web browser, e.g. on the console, during tests or during batch processes.
You will often want to access Power.current
from another model, to e.g. iterate through the list of accessible users:
class UserReport
def data
Power.current.users.c...
Consul: Dynamically access and query powers for a given name, model class or record
Consul 0.6.1+ gives you a way to dynamically access and query powers for a given name, model class or record.
A common use case for this are generic helper methods, e.g. a method to display an "edit" link for any given record
if the user is authorized to change that record:
module CrudHelper
def edit_record_action(record)
if current_power.include_record?(:updatable, record)
link_to 'Edit', [:edit, record]
end
end
end
You can find a full list of available dynamic calls bel...
Understanding race conditions with duplicate unique keys in Rails
validates_uniqueness_of
is not sufficient to ensure the uniqueness of a value. The reason for this is that in production, multiple worker processes can cause race conditions:
- Two concurrent requests try to create a user with the same name (and we want user names to be unique)
- The requests are accepted on the server by two worker processes who will now process them in parallel
- Both requests scan the
users
table and see that the name is available - Both requests pass validation and create a user with the seemingly available name...
Running "bundle update" without arguments might break your application
Calling bundle update
(without arguments) updates all your gems at once. Given that many gems don't care about stable APIs, this might break your application in a million ways.
To stay sane, update your gems using the applicable way below:
Projects in active development
Update the entire bundle regularily (e.g. once a week). This ensures that your libraries are up-to-date while it's easy to spot major version bumps which may break the app.
Projects that have not been updated in a while
- [Update a single gem conservatively](htt...
Geordi: run a capistrano task on all stages
Geordi now has a script that runs capistrano with all known deploy targets (i.e. staging, production...).
Use with
geordi capistrano deploy:migrations
or
geordi capistrano deploy
The abbrevation geordi cap ...
works as well.
Using Apache Benchmark (ab) on sites with authentication
Apache HTTP server benchmarking tool (ab
) is a nice tool to test performance on sites delivered by HTTP. If the site you're about to test is placed behind a login, follow these steps to successfully use ab
on it.
- Open the site to test in the browser of your choice. Do not login yet.
- Use developer tools to show all cookies used by the site. (Chrome: Ctrl+Shift+i, open the 'Resources' tab and click on the site below 'Cookies' on the left. Firefox: Right-click on the site, open 'We...
Git: How to stash with a custom message
If you say git stash
, your stashed changes will be identified with an automatically generated message:
$ git stash
Saved working directory and index state WIP on master: 77af0df Merge branch 'production'
While this is okay to temporarily stash away stuff, you may want a better identifier for your changes so you can find them more easily if you stash often.
Of course, there is a way to do it with git:
$ git stash save doing crazy things
Saved working directory and index state On master: doing crazy things
Note that you n...
Consul 0.5.0 is faster for admins, allows to define multiple powers at once
When calling a scope like current_power.user?(user)
, Consul will no longer trigger a query if the users
power selects all records (SELECT * from users
). This should make such checks much faster for users who can access many records, like admins.
You can now define multiple powers at once:
power :users, :updatable_users, :creatable_users do
...
end
CSS Explain - A tool which calculates CSS selector specificity
Example input:
li.active a:link
Example output (specificity):
| 0 | 2 | 2 |
See also: https://www.codecaptain.io/tools/css-specificity-calculator