...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 other_user_names = party.users.collect(&:name) message = "You've been...

index fea2bca..0000000 --- a/app/models/content_migration/photo.rb +++ /dev/null @@ -1,42 +0,0 @@ -class ContentMigration::Photo < ActiveRecord::Base # ... # ... diff --git a/app/models/content_migration/record/photo.rb b/app/models/content_migration/record/photo.rb new file mode 100644 index 0000000..2c8b70a --- /dev/null +++ b/app/models/content_migration/record/photo.rb...

...class ContentMigration::Record::Photo < ActiveRecord::Base # ... After: The diff shows that a file has been renamed. $ git diff -M diff --git a/app/models/content_migration/photo.rb b/app/models/content_migration/record/photo.rb similarity index 95% rename from app/models/content_migration/photo.rb

...Rails internal (per-request) cache. For this, wrap your code with a call to ActiveRecord::Base.uncached. For example, as an around_filter: def disable_cache ActiveRecord::Base.uncached do yield

makandra dev

...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...

...traits "authentication" and "permissions". In Modularity 1 you now had to say: class User < ActiveRecord::Base does 'user/authentication' does 'user/permissions' end Because Modularity 2 traits are vanilla modules, you can...

apidock.com

Note: ActiveRecord::Base#becomes has a lot of quirks and inconsistent behavior. You probably want to use ActiveType.cast instead. ActiveRecord models have with a method becomes(klass) which you can...

...methods list drastically more relevant. You can also try subtracting other base classes like ActiveRecord::Base.methods etc. To further narrow it down you can also just look at public methods...

...complete mess that makes your code hard to read. Consider these classes: class Topic < ActiveRecord::Base def title "A title" end def category "Topic category" end end class Post < ActiveRecord...

...Alternative to def_delegators When working with Rails, use delegate...

...:to =>...

class Post < ActiveRecord::Base belongs_to :topic delegate :title, :category, :to => :topic end That's a lot prettier...

...that has a Carrierwave Uploader mounted will take care of the validation: class User < ActiveRecord::Base mount_uploader :portrait, ImageUploader validate :valid_content_type private def valid_content_type errors.add...

...such validations directly on the Uploader itself, by hooking into a callback: class User < ActiveRecord::Base mount_uploader :portrait, ImageUploader end class ImageUploader < BaseUploader before :cache, :check_mimetype private

gist.github.com

...this script for easy debugging require 'pry' # Connect to an in-memory sqlite3 database ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ':memory:' ) # Define a minimal database schema ActiveRecord::Schema.define do

t.belongs_to :show, index: true end end # Define the models class Show < ActiveRecord::Base has_many :episodes, inverse_of: :show end class Episode < ActiveRecord::Base belongs_to :show...

...a Holiday it caches the current number of holidays in its region: class Region < ActiveRecord::Base has_many :holidays validates_numericality_of :holiday_count end class Holiday < ActiveRecord::Base

...to forbid #region_id from being changed after the Holiday was created: class Holiday < ActiveRecord::Base belongs_to :region does 'frozen_attribute', :region_id # ... end The attached trait will add...

...classes. These two migrations do the same: class Migration1 < ActiveRecord::Migration[5.2] class User < ActiveRecord::Base; end def up add_column :users, :trashed, :boolean User.update_all(trashed: false) end

...parts from EncryptableRecord # where extracted to reduce the amount of Rails magic. class User < ActiveRecord::Base end def deterministic_key ActiveRecord::Encryption.config.deterministic_key end def up User.find_each do |user...

...class nested in another is not supported Assuming an architecture like this: class Building < ActiveRecord::Base end class Building::Room < ActiveRecord::Base belongs_to :building end

...does not override a method with the same name. Take this example: class Project < ActiveRecord::Base def user "foo" end belongs_to :user end Project.new.user still returns "foo".

...for this is that what belongs_to does is actually this: class Project < ActiveRecord::Base include FeatureMethods def user "foo" end end module Project::FeatureMethods def user # association getter goes...

...avoid logging PII in SQL queries ActiveSupport.on_load(:active_record) do Rails.application.config.after_initialize do ActiveRecord::Base.filter_attributes = Rails.application.config.filter_parameters end

...you would validate presence of parent object id, like in this example: class Parent < ActiveRecord::Base has_many :nested, :inverse_of => :parent accepts_nested_attributes_for :nested end

...ActiveRecord::Base belongs_to :parent validates_presence_of :parent_id # <- end With the parent already persisted creating nesteds still works fine. But one will encounter a 'parent id missing' error...

...would be to handle the cast yourself: class ChangeAnIntegerColumnToString < ActiveRecord::Migration[6.1] class User < ActiveRecord::Base; end def up change_column :users, :address_number, 'varchar USING CAST(rating AS varchar...

...after the association. As an example, assume you have these two models: class Group < ActiveRecord::Base has_many :users end class User < ActiveRecord::Base validates_presence_of :group_id

... end # app/models/document/uploader.rb class Document::Uploader < CarrierWave::Uploader::Base ... end # app/models/document.rb class Document < ActiveRecord::Base mount_uploader Document::Uploader end # app/models/contract.rb class Contract < ActiveRecord::Base mount_uploader Contract::Document...

...map.resources :notes, :member => { :attachment => :get } Your attachment can be configured like this: class Note < ActiveRecord::Base has_attached_file :attachment, :path => ":rails_root/storage/:rails_env/attachments/:id/:style/:basename.:extension"

...You can now use the hashed_path interpolation in your Paperclip attachments: class Note < ActiveRecord::Base attachment_virtual_path = "/system/attachments/:rails_env/:hashed_path/:id/:style/:basename.:extension" attachment_real...

# Vehicle # Vehicle::Car # Vehicle::Bike class MyMigration < ActiveRecord::Migration[6.1] class Vehicle < ActiveRecord::Base def self.find_sti_class(type_name) super(name) end end class Car < Vehicle

...a model User with settings stored as YAML in a single column: class User < ActiveRecord::Base typed_store :settings, coder: YAML do |s| s.string :lang s.integer :show_number_of_posts...

...language. So let's rename the settings key: class RenameLanguageKeyInUser < ActiveRecord::Migration class User < ActiveRecord::Base def rename_settings_key!(from, to) from, to = from.to_s, to.to_s old_settings...

...second scope will overwrite (and not join!) conditions from the first scope: class Contract < ActiveRecord::Base named_scope :with_region, proc { |region_id| { :conditions => { :region_id => region_id } } } end >> Contract.with...

...The problem in detail Consider this Rails class and the following articles: class Article < ActiveRecord::Base named_scope :available, :conditions => { :state => [ 'unassigned', 'draft' ] } end #<Article id: 1, title: "Cooking noodles...

...completed, you have to obtain a explicit row lock ("pessimistic lock") within a transaction. ActiveRecord::Base.transaction do obj = Model.find(23, :lock => true) ... end and ActiveRecord will ask the database to...