Showing posts with label Active record. Show all posts
Showing posts with label Active record. Show all posts

Wednesday, 20 June 2012

difference between update_attribute and update_attributes

Hi,

update_attribute and update_attributes both are used to update the object without having explicitly Active Record to update.

The main difference between them is update_attribute will not call validations and callbacks, it will skip validations and callbacks while updating the record.

Let me explain clearly

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2614
       def update_attribute(name, value)
         send(name.to_s + '=', value)
         save(false)
       end


In the above parameter that was passing for the save is false. i.e  save(perform_validation = false)). So it will skip the validations and there by callbacks.


Coming to update_attributes

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2621
       def update_attributes(attributes)
         self.attributes = attributes
         save
       end

In the above case we are not passing any parameter for the save. So it will be default 'true'. So it will call the validations.

Important point at here is, we should choose update_attribute mainly for updating Boolean column datatypes, where it is not required that much validations.

Here is the syntax that should be used for update_attribute

@user.update_attribute(:status, true)

The main goal of update_attribute is to bypass the stuff and make the update operation fast.




Thank You,
Uma Mahesh.

Wednesday, 30 May 2012

active record update_all class method

Hi,

Here is the method in Active Record that updates all records. You can update records based on condition also.


update_all(updates, conditions = nil, options = {})

ex:
1) Updating all user records with status to active

    User.update_all(:status => 'active')

    This will return the records count that were updated.


2)  Updating records based on condition
   
     User.update_all(:status => 'active', ['title like ?', 'uma'])





Thank You,
Uma Mahesh.


 

Thursday, 24 May 2012

Count relation between models in rails using counter_cache option

I have a User with has_many articles. In order to display(count) number of articles created by user I will call @user.articles.count.
It will internaly run sql query on articles table. In order to eliminate the external query for displaying the count(i.e number of articles) active record associations provides usefull option for that.


Say a User has_many articles. In the articles model, add a line blongs_to :user, counter_cache: true. Add an integer column to the user table named articles_count. Whenever you create a article, the counter will be updated. See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to (:counter_cache section).

:counter_cache
Caches the number of belonging objects on the associate class through the use of increment_counter and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it’s destroyed. This requires that a column named #{table_name}_count (such as comments_count for a belonging Comment class) is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing a column name instead of a true/false value to this option (e.g., :counter_cache => :my_custom_counter.) Note: Specifying a counter cache will add it to that model’s list of readonly attributes using attr_readonly.


Thank you,
Uma Mahesh

Tuesday, 10 April 2012

Active Record Queries in Rails 3


Hi,

Rails 3 has Introduced many methods in ActiveRecord.

Here is the list of Active Record Queries in Rails 3 that I have used in my daily application developement.

    subscriptions = Subscription.where(
        :renewal => (Date.today-6)..(Date.today),
        :status => 'pending',
        :retry_count => 0..3,
        :retry_date => NIL )

 
   In the above query, 'renewal' column is a date datatype. By running query with (Date.today-15)..(Date.today) will fetch the records inbetween those dates.



Thank You,
Uma Mahesh    



Finding null records from date datatype column in postgres database


Hi,

While working with Postgres I had faced issue with query with date data type. When I try to fetch records with date column as null as below

subscriptions = Subscription.where(:retry_date => ' ' )

I have got the below error

PG::Error: ERROR: invalid input syntax for type date:

I came to see we cannot find the records through Active record as above.

By googling I found the way to fetch the records as below

subscriptions = Subscription.where(:retry_date => NIL )

Thank You,
Uma Mahesh.

Wednesday, 7 March 2012

usage of "changed_attributes" method in active record


Hi,

changed_attributes method provides a useful functionality to check the value that was updated in a column in before the object being saved.

These methods available under the "Active Model Dirty"

Here is the clear explanation on it.


person = Person.find_by_name('Uma Mahesh')
person.changed?       # => false

person.name = 'Varma'
person.changed?       # => true
person.name_changed?  # => true
person.name_was       # => 'Uma Mahesh'
person.name_change    # => ['Uma Mahesh', 'Varma']


A clear explanation of these methods were explained in the url :



http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changed_attributes
This method can be used to check the column value was updated or not. If you want to check the specific column value was update or not, this can be done by as below. 

In your model:

before_update :update_image_count_counter


  def update_image_count_counter
    if changed_attributes.keys.include?("image_count")
       # your required code comes here
    end
  end



Thank You,
Uma Mahesh