active-record Blogs
Written by Kiprosh, team of passionate and disciplined craftsmen turning your ideas into reality.
Kiprosh is now part of LawLytics
Written by Kiprosh, team of passionate and disciplined craftsmen turning your ideas into reality.
Performing an action via a callback is fairly easy and doable. Sometimes requirement may be a bit enhance that we need to track every change now and then. On the same note, if we have associations and we wanted to make some changes that needs to be reflected on previous and new values, this dirty concepts can save our time. This module gives a way to track changes done in an active-record object. By default, rails include ActiveRecord::Dirty this module. This gives many powerful methods that helps us to track attribute changes. This methods are based on the attribute
This is an awesome link on how to setup attributes on ActiveRecord LINK: 5-ways to set attributes And I want to mention one trick about active record: When we try to assign a value to active record object like class A In case of any queries, post your queries in comments.
ActiveRecord::Base#find_in_batches. This lets you iterate over all the records in cursor-like fashion (only retrieving a set number of records at a time into the memory): @Subscription.find_in_batches(batch_size => 100 ) { |subs| subs.each { |s| ... } }@ iterate over all subscriptions in chunks of 100 find_in_batches supports scopes @class Subscription < ActiveRecord::Base scope :expired, :conditions => { :expired => true } end @ @Subscription.expired.find_in_batches(:batch_size => 100 ) { |subs| ... }@ _Disadvantage: _ You can’t specify :order or :limit in the options. Where to use it: Large Dataset, where you need to loop through
What is Mass Assignment? Assigning multiple attributes of a record with params received from the application within a single query. For example,{:user => {:first_name => "FirstName", :last_name => "LastName", :role => "admin"}} So while creating a new record in User table, we specify as => User.create(params[:user]) In the above query, rails gives the freedom for one-to-one mapping of params attributes with model-record attributes. Lets say, we don't explicitly specify as User.create(:first_name => params[:user][:first_name], :last_name => params[:user][:last_name].......). Such assignments