patbenatar/jquery-nested_attributes
jQuery plugin that makes it easy to dynamically add and remove records when using ActiveRecord's nested attributes.
Discarding cached SQL query results in ActiveRecord
ActiveRecord caches results of SQL queries. If you want to discard the cached results for one model, you can call MyModel.connection.clear_query_cache.
Retrieving the class an ActiveRecord scope is based on
Edge Rider gives your relations a method #origin_class that returns the class the relation is based on.
This is useful e.g. to perform unscoped record look-up.
Post.recent.origin_class
# => Post
Note that #origin_class it roughly equivalent to the blockless form of #unscoped from Rails 3.2+, but it works consistently across all Rails versions. #unscoped does not exist for Rails 2 and is broken in Rails 3.0.
What's new in edge Rails: Active Record enums
Declare an enum attribute where the values map to integers in the database, but can be queried by name.
Why Ruby Class Methods Resist Refactoring
In a nutshell:
- Splitting a long method into sub methods is easier in instances since it is in classes. Since you must not save state in a class, you need to pass around context as a long chain of parameters again and again.
- If your public API has a single entry point, you can still have a class-level method that takes care of constructing the instance etc. So it's all win.
Why your previous developer was terrible
When you, as a developer, look at the choices used to build a particular application, you’re blown away at the poor decisions made at every turn. “Why, oh why, is this built with Rails when Node.js would be so much better?” or “how could the previous developer not have forseen that the database would need referential integrity when they chose MongoDB?” But what you may not realize is that you are seeing the application as it exists today. When the previous developer (or team) had to develop it, they had to deal with a LOT of unknowns. They...
BrowserStack has browser plugins for local testing
Local testing allows you to test your private and internal servers using the BrowserStack cloud, which has support for firewalls, proxies and Active Directory.
ActiveRecord: validate_uniqueness_of is case sensitive by default
By default, Rails' validates_uniqueness_of does not consider "username" and "USERNAME" to be a collision. If you use MySQL this will lead to issues, since string comparisons are case-insensitive in MySQL.
(If you use PostgreSQL, read this instead.)
Say you have a user model
class User < ActiveRecord::Base
validates_uniqueness_of :name
end
with a unique index in the database.
If you try to create the users "user" and "USER", this will not trigger a validation error, but may fail with an SQL error due ...
all_blank_except for accepts_nested_attributes_for
Put the attached file to config/initalizers to ignore some fields for rejecting nested records (e.g. hidden input fields).
class Post < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments, :reject_if => all_blank_except(:position, :other_nested_attrs)
end
Your Rails sandbox console
Just found out about a great feature in Rails that seems to be around since Rails 2. Start a console with the --sandbox (or -s) parameter:
rails console --sandbox
All changes you make to the database will be rolled back on exit.
Warning
Changes beyond the database (deleting files, sending emails, etc) cannot be rolled back!
Don't ever use the float type for database columns
Like in any language, a FLOAT will eventually corrupt data due to rounding errors.
Please use DECIMAL, which has well-defined behavior for rounding and range overflows.
Using Arel to Compose SQL Queries
Arel is a library that was introduced in Rails 3 for use in constructing SQL queries. Every time you pass a hash to where, it goes through Arel eventually. Rails exposes this with a public API that we can hook into when we need to build a more complex query.
[Openstack] "Failed to schedule_prep_resize: No valid host was found." when trying to resize an instance
If you get this error while trying to resize an openstack instance:
# nova resize fooinstance 16 --poll
==> /var/log/nova/nova-scheduler.log <==
2014-01-30 17:40:34 WARNING nova.scheduler.manager [req-aaaaaaa-bbbb-cccc-dddd-1ed34b64adef bajd7394hftgs71dba31d642342effa0f bfe2djhg6538sg384jgb82ks070ce0b] Failed to schedule_prep_resize: No valid host was found.
2014-01-30 17:40:34 WARNING nova.scheduler.manager [req-aaaaaaa-bbbb-cccc-dddd-1ed34b64adef bajd7394hftgs71dba31d642342effa0f bfe2djhg6538sg384jgb82ks070ce0b] Setting ...
Bash: Setting the title of your terminal tab
If your terminal has many tabs, you'll want to keep them organized. To change their title from the prompt, run this function:
function tab_title {
if [ -z "$1" ]
then
title=${PWD##*/} # current directory
else
title=$1 # first param
fi
echo -n -e "\033]0;$title\007"
}
Put it into your ~/.bashrc to have it always available. Adjust to your needs.
Usage
$> tab_title
# title set to the current directory's name
$> tab_title new_title
# title set to "new_title"
Auto-setting the title
=================...
How to load only a subset of a massive MySQL dump
I had a huge MySQL dump that took forever (as in: days) to import, while I actually just wanted to have the full database structure with some data to use on my development machine.
After trying several suggestions on how to speed up slow MySQL dump imports (which did not result in any significant improvement), I chose to import just some rows per table to suffice my needs. Since editing the file was not an option, I used a short Ruby script to manage that.
Here is how:
pv huge.dump | ruby -e 'ARGF.each_line { |l| m = l.match(/^INSERT ...
Don't use "self" as a Javascript variable
You might sometimes use self to capture the context of this before it is destroyed by some function.
Unfortunately self is also an alias for window, the global top-level object. Save your future self some headaches and use another name like me instead (Coffeescript chose to use _this).
The new Modularity 2 syntax
We have released Modularity 2. It has many incompatible changes. See below for a script to migrate your applications automatically.
There is no does method anymore
We now use traits with the vanilla include method:
class Article < ActiveRecord::Base
include DoesTrashable
end
When your trait has parameters, use square brackets:
class Article < ActiveRecord::Base
include DoesStripFields[:name, :brand]
end
Note how you ...
Careful with '||=' - it's not 'memoize'
When you do something like this in your code:
def var_value
@var ||= some_expensive_calculation
end
Be aware that it will run some_expensive_calculation every time you call var_value if some_expensive_calculation returns nil.
This illustrates the problem:
def some_expensive_calculation
puts "i am off shopping bits!"
@some_expensive_calculations_result
end
When you set @some_expensive_calculations_result to nil, ||= runs some_expensive_calculation every time....
Threads and processes in a Capybara/Selenium session
TLDR: This card explains which threads and processes interact with each other when you run a Selenium test with Capybara. This will help you understand "impossible" behavior of your tests.
When you run a Rack::Test (non-Javascript) test with Capybara, there is a single process in play. It runs both your test script and the server responding to the user interactions scripted by your test.
A Selenium (Javascript) test has a lot more moving parts:
- One process runs your test script. This is the process you...
Careful when writing to has_many :through associations
tl;dr: Using has_many associations with a :through option can lead to lost or duplicate records. You should avoid them, or only use them to read records.
Consider this:
class User < ActiveRecord::Base
end
class Party < ActiveRecord::Base
has_many :invitations
has_many :users, through: :invitations, include: :user, order: 'users.name'
end
class Invitation < ActiveRecord::Base
belongs_to :party
belongs_to :user
after_create :send_invite
def send_invite
...
Auto-coerced virtual attributes with Virtus
We've since created ActiveType which has a restricted subset of Virtus' features. It might be enough for your needs.
We sometimes give our ActiveRecord models virtual attributes for values that don't need to be stored permanently.
When such a virtual attribute should contain integer values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that Rails would give you if it ...
How to silence "I18n.enforce_available_locales" deprecation warnings
Before Rails 3.2.14, when supplying an invalid locale to I18n, it would fall back to its config.i18n.default_locale (which is :en by default). Eventually, this will be changed to raise an error by default -- for now, it shows a deprecation warning.
Since Rails 3.2.14 and 3.2.15 did not include security updates, you might not have applied them and probably now encounter these deprecation warnings after upgrading to 3.2.16 (or 4.0.2):
[deprecated] I...
Cancelling the ActiveRecord callback chain
| Goal | Within before_*
|
Within after_*
|
|---|---|---|
| Cancel later callbacks | throw :abort |
throw :abort |
| Rollback the transaction | throw :abort |
raise ActiveRecord::Rollback |
When a callback raises an error
Exceptions raised in callbacks always rollback the transaction, but only exceptions that are not ActiveRecord::Rollback will bubble up to the caller.
Further readi...
howto fix spreewald issue „database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified)“
This error occurs when you already have a database.yml which defines the database for the cucumber environment instead of test. (Spreewald database.sample.yml has changed)
Fix
Change cucumber to test in your databse.yml
test: # <---
adapter: mysql2
database: spreewald_test
encoding: utf8
host: localhost
username: root
password: password