When you eagerly load an association list using the .include
option, and at the same time have a .where
on an included table, two things happen:
where
condition, even though you only wanted to use the where
condition to filter the containing model.The second case's behavior is mostly unexpected, because pre-loaded associations usually don't care about the circumstances under whi...
When using virtual attributes, the attached trait can be useful to automatically copy errors from one attribute to another.
Here is a typical use case where Paperclip creates a virtual attribute :attachment
, but there are validations on both :attachment
and :attachment_file_name
. If the form has a file picker on :attachment
, you would like to highlight it with errors from any attribute:
class Note < ActiveRecord::Base
has_attached_file :attachment
validates_attachment_presence :a...
In modern Rails versions you can also use ActiveRecord's pluck
method.
>> User.active.pluck(:id)
=> [1, 5, 23, 42]
If you are plucking from the id
column in particular you can also say:
>> User.active.ids
=> [1, 5, 23, 42]
For a DISTINCT
selection, use distinct
on your scope (not the resulting array).
>> Article.distinct.pluck(...
There are two distinct ways of commenting Haml markup: HTML and Ruby.
This will create an HTML comment that will be sent to the client (aka browser):
/= link_to 'Example', 'www.example.com'
This produces the following HTML:
<!-- = link_to 'Example', 'www.example.com' -->
Only use this variant if you need the comment to appear in the HTML.
This will comment code so it will not be sent to the client:
-# = link_to 'foo'
99% of the time you'll be adding notes f...
config/application.rb
config/environment.rb
before the initialize!
call (we don't usually edit this file)environments/production.rb
config/initializers/*.rb
config/environment.rb
after the initialize!
call (we don't usually edit this file)app
config/preinitializer.rb
(if it exists)environment.rb
, code above the Rails::Initializer.run
blo...Sometimes you want to fetch associations for an ActiveRecord that you already loaded, e.g. when it has deeply nested associations.
Edge Rider gives your models a static method preload_associations
. The method can be used to preload associations for loaded objects like this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@user.preload_associations(threads: { posts: :author }, messages: :sender)
end
end
The attached initializers re...
When you need to add a event listener to hundreds of elements, this might slow down the browser.
An alternative is to register an event listener at the root of the DOM tree (document
). Then wait for events to bubble up and check whether the triggering element (event.target
) matches the selector before you run your callback.
This technique is called event delegation.
Because you only register a single listener, registering is ...