Rails 7 supports tracking of belongs_to association

One of the most convenient features of Rails is the ability to track attribute changes. Rails 7 is releasing soon and bringing in a lot of new features as a treat for developers. One of the many features that Rails 7 is introducing, is that we can also track the associated object. This Rails ActiveRecord specific PR has added two methods for tracking the changes for the belongs_to association. In this article, we will discuss these two new methods with the help of examples. 1. association_changed?The association_changed? method tells if a different associated object has been

Automatic counter-cache issue with has-many association in Rails 4.2.x

Recently while working on one of our project there was an requirement of tracking count of records associated with has-many association. But also there was "is_hidden" flag set on some of the records which I do not suppose to count in counter as those were hidden records. So default counter_cache option of rails active-record was not appropriate in this case which automatically counts and caches the number of associated records and keeps cache updated. Refer following model code for this. class Order < ActiveRecord::Base belongs_to :customer, counter_cache: true end class Customer < ActiveRecord:

Things which Rails could do but I didn't know.

Run Helper methods in the console $rails c => helper.number_to_currency(100) => "$100.00" => helper.time_ago_in_words(3.days.ago) => "3 days" Shorthand Migrations $ rails g resource person first_name:string last_name:string email:string token:string You can write above command as- $ rails g resource person first_name last_name email token Both will generate same migration: class CreatePeople Add Indexes to migrations $rails g resource person first_name:index last_name email:uniq token class CreatePeople true end end Add Associations to migrations $ rails g resource company person:references name description:text We can

Polymorphic associations

Consider a scenario where multiple models has 1 to N relationship with one model. For example. Consider models like School, College, Event and Semester are having multiple relationship with a single model i.e Student. It will not be a good idea to have multiple foreign keys to student model like school_id, college_id, event_id and semester_id into one table. So whenever you have a scenario like this, you have to follow polymorphic associations. For example: In your models i.e school.rb, college.rb, semester.rb and event.rb, define something like this: class School <