Understand ActiveRecord::ReadOnlyRecord error
When you load a record with find options that have SQL fragments in :select
or :joins
, ActiveRecord will make that record read-only. This is a protective measure by Rails because such a record might have some additional attributes that don't correspond to actual table columns.
You can override that precaution by appending :readonly => false
to affected find options or scope options.
Fix AssociationTypeMismatch
When you're getting this error, one possibility is that you've created a select field for an association instead of the associated object's id. Example:
form.select :unit, Unit.for_select
will be expected to deliver a real Unit
object, whereas
form.select :unit_id, Unit.for_select
will make Rails typecast the String value from the select field to the unit's ID.
stefankroes's ancestry at master - GitHub
Ancestry is a gem/plugin that allows the records of a Ruby on Rails ActiveRecord model to be organised as a tree structure (or hierarchy). It uses a single, intuitively formatted database column, using a variation on the materialised path pattern. It exposes all the standard tree structure relations (ancestors, parent, root, children, siblings, descendants) and all of them can be fetched in a single sql query. Additional features are STI support, named_scopes, depth caching, depth constraints, easy migration from older plugins/gems, integrit...
How Exchange handles multipart/alternative emails
In Rails, you can very easily send emails with HTML and plaintext bodies.
However, if you're trying to debug those using your normal email account, you might be out of luck: For some reason, Exchange servers will simply throw away the plaintext part of your mail, and just save the html part.
Ruby: How to update all values of a Hash
There are many solutions, but a very concise one is this:
hash.merge!(hash) do |key, old_value, new_value|
# Return something
end
The block of merge!
will be called whenever a key in the argument hash already exists in the base hash. Since hash
is updated with itself, each key will conflict and thus allow you to modify the value of each key to whatever you like (by returning old_value
you'd get the behavior of Rails' reverse_merge!
, by re...
Unicorn: How to force a single threaded boot in development
Unicorn allows you to specify the maximum number of workers. In development this could be useful if you use a debugger, but do not want to overflow the console with other request like from ActionCable. Then just set the maximum number of workers to 1
and the other requests have to wait.
UNICORN_WORKERS=1 rails server
IRB: last return value
In the ruby shell (IRB) and rails console the return value of the previous command is saved in _
(underscore). This might come in handy if you forgot to save the value to a variable and further want to use it.
Example:
irb(main):001:0> 1 + 2
=> 3
irb(main):002:0> _
=> 3
irb(main):003:0> a = _
=> 3
YAML syntax compared with Ruby syntax
yaml4r is a juxtaposition of yaml documents and their Ruby couterpart. Thus, it does a great job as YAML-doc, e.g. when writing Rails locale files. Did you know that ...
-
<<
is a merge key (similar to&
in SASS) - there are variables, called aliases. Definition:
&alias Some content
, usage:*alias
.
Caveats
Specifying a key twice does not merge the sub keys, but override the first definition, e.g.
de:
car: # overridden
door: Tür
...
Login forms: Disable browser prompt to remember the password
In order to prevent the browser from asking whether to remember the password, give a form an autocomplete
attribute with the value off
:
<form "/session" method="post" autocomplete="off">
...
</form>
Rails example
form_for @model, :html => { :autocomplete => "off" } do |form|
"rake gettext:findpo" running forever
Under certain circumstances gettext_i18n_rails
will hit a near-infinite loop. This occured in Rails 2.3.5 with Haml 3.0.18 and fast_gettext 0.5.10.
gettext_i18n_rails
's Haml-Parser compiles the Haml code and delegates the parsing to ruby_parser
. Unfortunately, ruby_parser
appears to be confused when a string contains both escaped chars (that is, any unicode characters as ndash, umlauts etc.) and #{}
blocks, which makes it extremely slow.
The easiest "solution" we came up with was to replace all occurrences of UTF-8 chars wi...
[jruby] TruffleRuby Status, start of 2017
TruffleRuby is an experimental Ruby implementation that tries to achieve ~10x performance over MRI.
This has been on our radar for a while. They seem to have made significant progress running Rails, reducing start-up time and becoming runtime-independent of the JVM.
Also see [Running Optcarrot, a Ruby NES emulator, at 150 fps with the GUI!](https://eregon.me/blog/2016/11/28/optcarrot.htm...
The asset pipeline does not like files that look like fingerprints
If you have a file that looks like a precompilation fingerprint, the Rails asset pipeline will not see it. So don't have filenames like this:
8e21264d-f678-4005-b90c-8d8288a0d179.ttf
Check if an object is an ActiveRecord scope
Don't say is_a?(ActiveRecord::NamedScope::Scope)
because that is no longer true in Rails 3 and also doesn't match unscoped ActiveRecord classes themselves (which we consider scopes for all practical purposes).
A good way is to say this instead:
object.respond_to?(:scoped)
Boolean fields in migrations
If you want to update some records with boolean fields in a migration, always remember to set your values with field=#{quoted_true}
and field=#{quoted_false}
. The Rails methods quoted_false
and quoted_true
return the correct boolean representations for your database.
XHR is not JSON
When a Rails controller action should handle both HTML and JSON responses, do not use request.xhr?
to decide that. Use respond_to
.
I've too often seen code like this:
def show
# ...
if request.xhr?
render json: @user.as_json
else
# renders default HTML view
end
end
This is just plain wrong. Web browsers often fetch JSON via XHR, but they (should) also send the correct Accept
HTTP header to tell the server the data they expect to receive.
If you say request.xhr?
as a means for "wants JSON" you are ...
Cucumber does not find neither env.rb nor step definitions when running features in nested directories
Usually, Cucumber feature files live in features/
. When you group them in sub directories, make sure to add -r features
to the standard Cucumber options.
In Rails apps, Cucumber options are likely to be stored in config/cucumber.yml
.
Why your all.js is empty on staging or production
When you include a non-existing Javascript file, you probably won't notice it during development. But with caching active (on production or staging) Rails will write an empty all.js
file without complaining.
Bootswatch: Paper
Free Bootstrap theme resembling Material Design.
Bootswatch offers Sass and Less files, so the theme can easily be integrated into your usual Rails application.
Implements only Bootstrap features which means that some Material stuff is missing, but also that you can easily use or replace the theme.
Does not come with extra JavaScript; some effects like button click ripples are implemented via CSS.
Also check out their other themes which can be used in a similar fashion.
travisliu/traim: Resource-oriented microframework for RESTful APIs
Use Traim to build a RESTful API for your ActiveRecord models with very little code.
Traim assumes your API resources will map 1:1 to your ActiveRecord models and database tables. This assumption usually falls apart after a few months into a project, so be ready to replace your Traim API with something more expressive afterwards.
Traim outputs a Rack application which you can either serve standalone or mount into your Rails app.
RSpec 2.6 supports "any_instance" now
This finally works:
User.any_instance.should_receive(...)
as does
User.any_instance.stub(...)
Note: You won't have RSpec 2.6 if you're still working on Rails 2.
Sending raw JSON data to a member action in a controller spec
This is what worked for me in a Rails 4:
# JSON data as first argument, then parameters
patch :update, { some: 'data' }.to_json, id: id, format: :json
Don't use Ruby 1.9.2
Ruby 1.9.2 is very slow when loading files, especially starting Rails servers or running specs takes forever.
Do yourself a favor and upgrade to 1.9.3.
Ruby: Find the most common string from an array
This will give you the string that appears most often in an array:
names = %w[ foo foo bar bar bar baz ]
names.group_by(&:to_s).values.max_by(&:size).try(:first)
=> "bar"
This is very similar to the linked StackOverflow thread, but does not break on empty arrays.
Note that try
is provided by ActiveSupport (Rails). You could explicitly load activesupport
or use andand
on plain Ruby.
How to stub class constants in RSpec
Hint: There's another card with this helper for Cucumber features.
Sometimes you feel like you need to stub some CONSTANT you have defined in an other class. Since actually constants are called constants because they're constant, there's no way to easily stub a constant.
Here are three solutions for you.
Easiest solution
Rethink! Do you really need CONSTANT = %w[foo bar]
to be constant? In many cases, setting it as a...