Translate

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 


January 5, 2011

How to write case (switch) statements in Ruby

When I started coding in Ruby last year I found the "case" statement complicated. After years of writing in C++ and C# it was hard for me to remember Ruby's case syntax because it can do so much more than switch statements in C++ language.
Following section describes the capabilities and use of case in Ruby language.
I hope you find them useful.
How to write case (switch) statements in Ruby
switch/case syntax-es
    (Remember: Ruby uses "case" and "when"
    where other popular languages use "switch" and "case"):

    # Basically if/elsif/else (notice there's nothing
    # after the word "case"):
    # [variable =] is optional 
    [variable = ] case
    when bool_condition
      statements
    when bool_condition
      statements
    else # the else optional
      statements
    end
    
    # If you assigned 'variable =' before the case,
    # the variable now has the value of the
    # last-executed statement--or nil if there was
    # no match.  variable=if/elsif/else does this too.

    # It's common for the "else" to be a one-line
    # statement even when the cases are multi-line:
    [variable = ] case
    when bool_condition
      statements
    when bool_condition
      statements
    else statement
    end

    # Case on an expression:
    [variable = ] case expression
    when nil
      statements execute if the expr is nil
    when Type1 [ , Type2 ] # e.g. Symbol, String
      statements execute if the expr
      resulted in Type1 or Type2 etc.
    when value1 [ , value2 ]
      statements execute if the expr
      equals value1 or value2 etc.
    when /regexp1/ [ , /regexp2/ ]
      statements execute if the expr
      matches regexp1 or regexp 2 etc.
    when min1..max1 [ , min2..max2 ]
      statements execute if the expr is in the range
      from min1 to max1 or min2 to max2 etc.
      (use 3 dots min...max to go up to max-1)
    else
      statements
    end

    # When using case on an expression you can mix &
    # match different types of expressions. for example.,
    [variable =] case expression
    when nil, /regexp/, Type
      statements execute when the expression
      is nil or matches the regexp or results in Type
    when min..max, /regexp2/
      statements execute when the expression is
      in the range from min to max or matches regexp2
    end

    # You can combine matches into an array and
    # precede it with an asterisk. This is useful when
    # the matches are defined at run-time, not when
    # writing the code. The array can contain a
    # combination of match expressions
    # (strings, nil, regexp, ranges, etc.)
    [variable =] case expression
    when *array_1
      statements execute when the expression matches one
      of the elements of array_1
    when *array_2
      statements execute when the expression matches one
      of the elements of array_2
    end

    # Compact syntax with 'then':
    [variable =] case expression
    when something then statement
    when something then statement
    else statement
    end

    # Compact syntax with semicolons:
    [variable =] case expression
    when something; statement
    when something; statement
    else statement # no semicolon required
    end

    # Compact syntax with colons
    # (Note: no longer supported in Ruby 1.9)
    [variable =] case expression
    when something: statement
    when something: statement
    else statement # no colon required
    end

    # 1-line syntax:
    [variable = ] case expr when {Type|value}
      statements
    end

    # Formatting: it's common to indent the "when"
    # clauses and it's also common not to:
    case
      when
      when
      else
    end

    case
    when
    when
    else
    end