Enumerable#all? returns true
for an empty collection. This totally makes sense but you have to think about it when making assumptions on relations which might be empty.
[].all?(&:will_never_be_called_here) => true
class Researcher < ActiveRecord::Base
has_many :papers
end
class Paper
validates :topic, inclusion: { in: ['computer_science', 'mathematics', 'economy'] }
end
Easy goal: Delete all researches who write onl...
TL;DR Use user.update!(remove_avatar: true)
to delete attachments outside of forms. This will have the same behavior as if you were in a form.
As you know, Carrierwave file attachments work by mounting an Uploader
class to an attribute of the model. Though the database field holds the file name as string, calling the attribute will always return the uploader, no matter if a file is attached or not. (Side note: use #present?
on the uploader to check if the file exists.)
class User < ApplicationRecord
mount :avatar, ...
This is a small example on how you can check if your Postgres index can be used by a specific query in you Rails application. For more complex execution plans it might still be a good idea to use the same path of proof.
query = User.order(:last_name, :created_at).to_sql
puts query
# => SELECT "users".* FROM "users" ORDER BY "users"."last_name" ASC, "users"."created_at" ASC
add_index :users, [:last_name, :created_at]...
This is painful. Consider using Microsoft Office or switching careers. If you need to write < 20 letters consider doing it manually.
So you didn't listen and here it comes:
.ods
spreadsheet (.xls
, .xlsx
, .ods
). Use any columns that work for you, but be consistent. I like to use one column for the address, one column for the salutation line.This error is raised because your old database does not have a configured environment yet, which Rails 5 enforces.
If this error occurs while migrating your parallel test databases, make sure to update the parallel_tests
gem first: current versions fix this. If you're still using Cucumber < v3, the latest version of parallel_tests
will be 2.18.0.
You should avoid using application models in your migrations. But how else could you create records in a migration?
The most basic way is to write plain SQL, but since INSERT statements are no pleasant write for Rubyists, here is a simple wrapper:
The helper method below takes a table name and a hash of attributes, which it inserts into the specified table. Copy it over to your migration and profit!
private
def insert_record(table, **attributes)
attributes.merge!...
PostgreSQL's Common Table Expressions (CTEs) can be used to extract sub-queries from bulky SQL statements into a temporary table to be referenced instead.
This is most useful to avoid ugly joins or sub-selects. CTEs can be used for SELECT
, INSERT
, UPDATE
or DELETE
.
Example (from the PostgreSQL docs):
WITH regional_sales AS (
SELECT region, SUM(amount) AS total_sales
FROM orders
GROUP BY region
), top_regions AS (
SELECT region
FROM regional_sales
WHERE total_sales > (SE...
PostgreSQL supports the SQL OVERLAPS
operator. You can use it to test if two date ranges overlap:
=> SELECT ('2001-02-16'::date, '2001-12-21'::date) OVERLAPS
('2001-12-20'::date, '2002-10-30'::date);
overlaps
--------
true
An important caveat is that the date ranges are defined as start <= time < end
. As such the later date is not included in the range:
=> SELECT ('2001-02-16'::date, '2001-12-21'::date) OVERLAPS
('2001-12-21'::date, '2002-10-30'::date);
overlaps
--------
false
Also compar...
Git has two kind of tags:
Annotated tags are stored as full objects in the Git database. They’re checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG)
The following command will create a (lightweight) tag:
git tag v0.1
An annotated tag is created by:
git tag -a v0.1 -m "a special tag message"
A normal git push
will not push the tag. So in order to publish your (local) tags, you have to
git push --tags
`...
In most projects I know, Cucumber test suite speed is not an issue. Of course, running 350 features takes its time, but still each test for itself is reasonably fast. There is nothing you can do to fundamentally speed up such a test (of course, you should be using parallel_tests).
However, in projects that go beyond clicking around in a web GUI and checking results, there might be various measures to speed things up. Katapult tests for example could be sped up more than 4 times by re...
Requestb.in is a webservice that gives you a temporary URL you can use to test request. The page will automatically record and display the latest web request made to it.
We're usually running Ubuntu LTS versions. Sometimes newer hardware requires packages from more recent Ubuntu releases that only come with 6 months of support. If there is really no other way, it's possible to install packages from later Ubuntu releases
Caution: Pay really close attention to what you're doing. Depending on the package, this process may require upgrading a lot of dependencies, possibly breaking the system! You really should not do this unless you've carefully calculated the impact on your system
First,...
An end-to-end test (E2E test) is a script that remote-controls a web browser with tools like Selenium WebDriver. This card shows basic techniques for fixing a flaky E2E test suite that sometimes passes and sometimes fails.
Although many examples in this card use Ruby, Cucumber and Selenium, the techniques are applicable to all languages and testing tools.
Your tests probably look like this:
When I click on A
And I click on B
And I click on C
Then I should see effects of C
A test like this works fine...
When your public-facing application has a longer downtime for server maintenance or long migrations, it's nice to setup a maintenance page to inform your users.
When delivering the maintenance page, be very careful to send the correct HTTP status code. Sending the wrong status code might get you kicked out of Google, or undo years of SEO work.
Here are some ways to shoot yourself in the foot during maintenance:
Slides for Henning's talk on Sep 21st 2017.
print('script start')
html = get('/foo')
print(html)
print('script end')
Script outputs 'script start'
, (long delay), '<html>...</html>'
, 'script end'
.
print('script start')
get('foo', done: function(html) {
print(html)
})
print('script end')
Script outputs 'script start'
, `'...
If you are using PDFKit / wkhtmltopdf, you might as well want to use custom fonts in your stylesheets. Usually this should not be a problem, but at times they include misleading Meta-information that leads to a strange error in the PDF.
BrandonText-Regular
and BrandonText-Bold
. (With flawed Meta-information)You need to set the :inverse_of
option manually for relations that have an association to a polymorphic model. Otherwise you will not be able to save a record with a nested polymorphic association.
class Event < ApplicationRecord
has_many :letters, as: :record
end
class Letter < ApplicationRecord
belongs_to :record, polymorphic: true
end
event = Event.new.letters.build
event.save! # => ActiveRe...
RSpec allows defining methods inside describe
/context
blocks which will only exist inside them.
However, classes (or any constants, for that matter) will not be affected by this. If you define them in your specs, they will exist globally. This is because of how RSpec works (short story: instance_eval
).
describe Notifier do
class TestRecord
# ...
end
let(:record) { TestRecord.new }
it { ... }
end
# TestRecord will exist here, outside of the spec!
This will come bite you at least when you try to define a ...
Let's say you have a form that you render a few times but you would like to customize your submit section each time. You can achieve this by rendering your form partial as layout and passing in a block. Your template or partial then serves as the surrounding layout of the block that you pass in. You can then yield back the form to the block and access the form in your block.
record/_form.haml
= form_for record do |form|
...
.form-actions
yield(form)
In order to make your template record/_form.haml
accept a block whe...
FactoryBot allows a :class
option to its factory
definitions, to set the class to construct. However, this option is not supported for trait
s.
Most often, you can just define a nested factory instead of a trait, and use the :class
option there.
factory :message do
factory :reply, class: Message::Reply do
# ...
end
end
If you need/want to use traits instead (for example, it might make more sense semantically), you can not use a :class
on a trait
.
In that case, use initialize_with
to define the record's constr...
After loading a staging dump into development, you might get an ActiveRecord::EnvironmentMismatchError
when trying to replace the database (like rails db:drop
, rails db:schema:load
).
$ rails db:drop
rails aborted!
ActiveRecord::EnvironmentMismatchError: You are attempting to modify a database that was last run in `staging` environment.
You are running in `development` environment. If you are sure you want to continue, first set the environment using:
bin/rails db:environment:set RAILS_ENV=development
Starting with R...
If another session is accessing your database you are trying to reset or drop you might have seen the following error:
PG::ObjectInUse: ERROR: database "foo_development" is being accessed by other users
DETAIL: There is 1 other session using the database.
This could be the rails server, rubymine and many more. Beside terminating the session connection manually you can also find out the pid
and kill the process.
1. rails db
2. SELECT * FROM pg_stat_activity;
datid | 98359
datname | foo_developm...
return
to return from a method. return
accepts a value that will be the return value of the method call.break
to quit from a block and from the method that yielded to the block. break
accepts a value that supplies the result of the expression it is “breaking” out of.next
to skip the rest of the current iteration. next
accepts an argument that will be the result of that block iteration.The following method will serve as an example in the details below:
def example
puts yield
puts ...