Translate

April 18, 2012

Difference between update_attribute and update_column


We use update_attribute most of the time, update_column serves same purpose, there is below difference
  • update_attribute
  • It updates the single attribute with bypassing the validations.
  • update_column
  • It updates the single attribute with bypassing the validations as well as the callbacks.

Syntax of both are as follow:
Model.update_attribute :field, 'value'
Model.update_column :field, 'value'

update_column is added in the rails 3.2.1

In case if you need to use update_column in lower Rails version then you can apply simple patch given below.

module ActiveRecord
  module AttributeMethods
    def update_column(name, value)
      name = name.to_s
      self.class.update_all({ name => value }, self.class.primary_key => id) == 1
     end
   end
end

Related posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About

April 17, 2012

What is different in update_all, update, update_attribute, update_attributes methods of Active Record

We use Active Record update* methods regularly, following text explains the difference between all update* the methods

update(id,attributes)
Update single or multiple objects using update method of active record. When update method is called it invokes model based validation, and save the object when validation passes successfully else object is not save.
It accepts two arguments, id and attributes which need to update.
User.update(1,:first_name => "John",:last_name => "Turner")
same way you are able to update multiple objects.
User.update([1,2],[{:first_name => "John",:last_name => "Turner"},{:department => "admin"}])

update_all(attribute, conditions, options)
It updates the given attribute of object by invoking specified conditions and options like order, limit. This will not invoke validation rules, methods of the model.
User.update_all("department = admin, "user_role Like '%admin'",:limit => 10)

update_attribute
This method update a single attribute of object without invoking model based validation.
user = User.find_by_id(params[:id])
user.update_attribute :role,"admin_manager"

update_attributes
This method update multiple attribute of single object and also pass model based validation.
attributes = {:first_name => "Peter", :age => 30}
user = User.find_by_id(params[:id])
user.update_attributes(attributes)

I think this article helped you to understand different Active Record update* methods. And which method to use in specific situation.
If have any query or suggestion than simply leave the comment.

Related posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About

December 23, 2011

How to rollback Rails database migrations

When you want to perform database migrations in rails you use the following command:
rake db:migrate 

If you want to roll back your change you may need to find out what version your database is currently at and then roll back to a previous version:
To find the version use following command:
rake db:migration VERSION=? 

To roll back to previous version:
rake db:migrate VERSION=<version to roll back to>

To use it to roll back your most recent migration simply run:
rake db:rollback

Other posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About

November 13, 2011

Dropbox – echo 100000 | sudo tee /proc/sys/fs/inotify/max_user_watches

Dropbox - echo 100000 | sudo tee /proc/sys/fs/inotify/max_user_watches

Dropbox comes up with the error message:
echo 100000 | sudo tee /proc/sys/fs/inotify/max_user_watches

Unfortunately anything put in /proc/sys is not permanent and your back at square one on next boot. There are a couple of fixes it for the issue though.
1) Edit /etc/sysctl.conf and add the following:

# Fix for Dropbox
fs.inotify.max_user_watches=100000


2) Edit /etc/rc.local and add the following:

echo 100000 | tee /proc/sys/fs/inotify/max_user_watches
Any one will permanently fix the error (as far as I understand) I am using method 1.

This is a brief explanation of the issue that I found at http://forums.dropbox.com/topic.php?id=29130
This is from the "advanced" section of https://www.dropbox.com/help/145:
"Monitoring more than 10000 folders
The Linux version of the Dropbox desktop application is limited from monitoring more than 10000 folders by default. Anything over that is not watched and, therefore, ignored when syncing. There's an easy fix for this. Open a terminal and enter the following:
sudo sysctl fs.inotify.max_user_watches=100000 
This command will tell your system to watch up to 100000 folders. Once the command is entered and you enter your password, Dropbox will immediately resume syncing."

November 9, 2011

render vs redirect_to in Ruby on Rails

Here's what you need to know when you're deciding between a render and a redirect_to in your controller action

render
This will render a particular view using the instance variables available in the action.
For example if a render was used for the new action, when a user goes to /new, the new action in the controller is called, instance variables are created and then passed to the new view. Rails creates the html for that view and returns it back to the user's browser. This is what you would consider a normal page load.

redirect_to
This will send a redirect to the user's browser telling it to re-request a new URL as 302 redirect response. Then the browser will send a new request to that URL and it will go through the action for that URL, oblivious to the fact that it was redirected to. None of the variables created in the action that caused the redirect will be available to the redirected view. This is what happens when you click on 'Create' in a form and the object is created and you're redirected to the edit view for that object.

If you do not have a render or a redirect_to in your controller method for a particular action then Rails will automatically render the template for that action. For example if your action is new, rails will render the view for new: new.html.erb.

If you need to render another action's view, you can use render :action_name.

If you need the user to run a new action, use redirect_to :action => :action_name. For example if the user has clicked 'Create' and there are no errors in creating the object, you can use redirect_to :action => :show to show the successfully created object.

Related posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About

August 24, 2011

Difference between .nil?, .empty?, .blank?, .present?

I have been puzzled or confused with the method  nil?, empty?, blank? And present?
How do you do it differently?

nil? -> This can be used with any object will return true (true) when the object is not nil and false (false) if the object has something in it.

Example:.
nil. nil?
 # => true.
 [].nil?
 # => false.
 "".nil?
 # => false.
 "  ".nil?
 # => false.

empty? -> This can not be used with any object, this is valid for using with object of class array, Hashes and String. This will return true (true) if the object does not have any value at all.

    When empty? is used for nil object it will throw an error "NoMethodError".

When used with strings, arrays and hashes
    String length == 0.
    Array length == 0.
    Hash length == 0.

Example:.
[].empty?
 # => true.
 nil.empty?
 # => Undefined method.
 "".empty?
 # => true.
 "  ".empty?
 # => false
empty?
 # => false.

blank? ->
This can be used for any object and This will returns true if the object has a value of nil, false, empty, or a white space string.

Example:.
[]. blank?
 # => true.
 nil.blank?
 # => true.
 "".blank?
 # => true.
 "    ".blank?
 # => true.
 false.blank?
 # => true

present? -> This can be used with any object will be restored when the object has a value that is not nil, false, empty, or a white space string. This behave exact opposite of blank?

    blank? ! = present?

Example:.
[].present?
 # => false.
 nil.present?
 # => false.
 "".present?
 # => false.
 "  ".present?
 # => false.
 false.present?
 # => false.
Summary:

    nil? When the value is nil for each object.
    empty? To check for the empty string, array, hash.
    blank? To check the object has a value of nil
    present? The opposite of blank?

Finally, With different conditions you can choose best suited methods.
Note: .blank? and .present? are rails methods.

Related posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About

May 15, 2011

Import CSV file directly into MySQL

I got BIG csv containing thousands of records, and I need to put those in mysql table. Writing simple script would do the job, but I thought instead of writing a script to pull in information from a CSV file, I can link MYSQL directly to it and upload the information using the following SQL syntax.

Step 1:
Remove the CSV headers from the CSV file along with empty data.

Step 2:
Create a mysql table equivalent to the CSV headers.
CREATE TABLE inv_data ( id INT(11), description VARCHAR(100), 
            ...
             ...
      ); 

Step 3:
You can then import it into a MySQL table by running:
load data local infile 'inventory_data.csv' into table inv_data fields terminated by ','
enclosed by '"'
lines terminated by '\n

The enclosed by and lines terminated by are optional and can help if you have columns enclosed with double-quotes such as Excel exports, etc.

NOTE: If you get error saying :
ERROR 1148 (42000): The used command is not allowed with this MySQL version

Please start mysql using following command

mysql --local_infile=1 -u root -p