breaking into the unknown…


rake db:seed in rails

rake command is explained in this post . writing custom rake task is explained in this post.  db:seed is inbuilt rake task defined by rails. The rake db:seed command, basically execute whatever code you write in db/seeds.rb file of your application. Though can write any code in this file, by convention you should write code which populate your database with the basic data, for example: when ever your deploy your application somewhere, and create a new database for it, you want that user with admin credential must be present there. So you will write the code which create that user in this file. Below is the sample code which will create a user and assign admin role to him.

puts "********Seeding Data Start************"

admin = User.create(:first_name => 'System', :last_name => 'Admin', 
       :email => '', :password => 'sunpoweradmin', 
       :password_confirmation => 'sunpoweradmin', :source_system_id => 'systemadmin', 
       :source_system => 'LP',:entity_type => "Customer", :target_system => "OPENAM")

if admin.errors.blank?
    puts "***User #{admin.first_name} #{admin.last_name} created ***"
    admin.add_role :admin # add_role is method defined by rolify gem
    puts "***admin role assigned to #{admin.first_name} #{admin.last_name}***"
    puts "admin user failed to create due to below reasons:"
    admin.errors.each do |x, y|
       puts"#{x} #{y}" # x will be the field name and y will be the error on it

puts "********Seeding Data End************"

Now whenever you recreate your database, you just need to run below command to populate the database, with the basic data

$ rake db:seed RAILS_ENV=production

The correct order to setup database in production, with all the rake task available within db namespace is as below

$rake db:create RAILS_ENV=production

$rake db:migrate RAILS_ENV=production

$ rake db:seed RAILS_ENV=production

NOTE: You can replace the first two commands with $rake db:setup RAILS_ENV=production , it will run both create and migrate internally

=> COMPLETE LIST of rake db command in rails :

db:create creates the database for the current env
db:create:all creates the databases for all envs
db:drop drops the database for the current env
db:drop:all drops the databases for all envs
db:migrate runs migrations for the current env that have not run yet
db:migrate:up runs one specific migration
db:migrate:down rolls back one specific migration
db:migrate:status shows current migration status
db:migrate:rollback rolls back the last migration
db:forward advances the current schema version to the next one
db:seed (only) runs the db/seed.rb file
db:schema:load loads the schema into the current env’s database

db:schema:dump dumps the current env’s schema (and seems to create the db as well)

db:setup runs db:schema:load, db:seed
db:reset runs db:drop db:setup
db:migrate:redo runs (db:migrate:down db:migrate:up) or (db:migrate:rollback db:migrate:migrate) depending on the specified migration
db:migrate:reset runs db:drop db:create db:migrate


Leave a comment

what is rake in rails

rake is command line utility of rails. All commands available for rails are listed here . writing custom rake task is explained in this post . Below is the definition given for it in rails doc.

“Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.”

Putting in simple word : “rake will execute different tasks(basically a set of ruby code) specified in any file with .rake extension from comandline.” .

rake is a gem in itself and installation dependency of rails i,e whenever you install a rails rake gem get installed along with it.

rails provide a number of inbuilt task like : db:create, db:migrate etc, you have been familiar with. You can define your own task (see here) also. list of all the task can be seen with below command.

$ rake -T #below is the list of task with small description of what they do. when you install a gem say cucumber or rcov or any othet, if they have defined any rake task it will get listed here.basically below is the list of all task available to you : the built one, those provided by installed gems or custome task wriiten by you
rake about                                              # List versions of all Rails frameworks and the environment
rake assets:clean                                       # Remove compiled assets
rake assets:precompile                                  # Compile all the assets named in config.assets.precompile
rake cucumber                                           # Alias for cucumber:ok
rake cucumber:all                                       # Run all features
rake cucumber:ok                                        # Run features that should pass
rake cucumber:rerun                                     # Record failing features and run only them if any exist
rake cucumber:wip                                       # Run features that are being worked on
rake db:create                                          # Create the database from DATABASE_URL or config/database.yml
rake db:drop                                            # Drops the database using DATABASE_URL or the current Rails.env
rake db:fixtures:load                                   # Load fixtures into the current environment’s database.
rake db:migrate                                         # Migrate the database (options: VERSION=x, VERBOSE=false).
rake db:migrate:status                                  # Display status of migrations
rake db:rollback                                        # Rolls the schema back to the previous version (specify steps w/ STEP=n).
rake db:schema:dump                                     # Create a db/schema.rb file that can be portably used against any DB
rake db:schema:load                                     # Load a schema.rb file into the database
rake db:seed                                            # Load the seed data from db/seeds.rb
rake db:setup                                           # Create the database, load the schema, and initialize with the seed data
rake db:structure:dump                                  # Dump the database structure to db/structure.sql.
rake db:version                                         # Retrieves the current schema version number
rake doc:app                                            # Generate docs for the app — also available doc:rails
rake jquery_ui_themes:import:google_cdn[version,theme]  # Import themes from Google CDN
rake jquery_ui_themes:import:themeroller[path,name]     # Import jQuery themeroller theme
rake loanpath:on_db_refresh                             # Actions to do after the db refresh
rake log:clear                                          # Truncates all *.log files in log/ to zero bytes
rake middleware                                         # Prints out your Rack middleware stack
rake notes                                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
rake notes:custom                                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
rake paperclip:clean                                    # Cleans out invalid attachments.
rake paperclip:refresh                                  # Refreshes both metadata and thumbnails.
rake paperclip:refresh:metadata                         # Regenerates content_type/size metadata for a given CLASS
rake paperclip:refresh:missing_styles                   # Regenerates missing thumbnail styles for all classes using Paperclip.
rake paperclip:refresh:thumbnails                       # Regenerates thumbnails for a given CLASS
rake rails:template                                     # Applies the template supplied by LOCATION=(/path/to/template) or URL
rake rails:update                                       # Update configs and some other initially generated files
rake rails_admin:disable_initializer                    # Disable rails_admin initializer / Disable rails_admin initializer
rake rails_admin:install                                # Install rails_admin / Install rails_admin
rake rails_admin:prepare_ci_env                         # CI env for Travis / CI env for Travis
rake rails_admin:uninstall                              # Uninstall rails_admin / Uninstall rails_admin
rake routes                                             # Print out all defined routes in match order, with names.
rake secret                                             # Generate a cryptographically secure secret key
rake spec                                               # Run all specs in spec directory (excluding plugin specs)
rake spec:controllers                                   # Run the code examples in spec/controllers
rake spec:helpers                                       # Run the code examples in spec/helpers
rake spec:lib                                           # Run the code examples in spec/lib
rake spec:mailers                                       # Run the code examples in spec/mailers
rake spec:models                                        # Run the code examples in spec/models
rake spec:rcov                                          # Run all specs with rcov
rake spec:requests                                      # Run the code examples in spec/requests
rake spec:routing                                       # Run the code examples in spec/routing
rake spec:views                                         # Run the code examples in spec/views
rake stats                                              # Report code statistics (KLOCs, etc) from the application
rake time:zones:all                                     # Displays all time zones, also available: time:zones:us
rake tmp:clear                                          # Clear session, cache, and socket files from tmp/
rake tmp:create                                         # Creates tmp directories for sessions, cache, sockets, and pids

In the above command we have passed -T option which list all the tasks for us. list of other available option for rake can be listed with –help option as below

$ rake –help
rake [-f rakefile] {options} targets…

Options are …
–backtrace=[OUT]            Enable full backtrace.  OUT can be stderr (default) or stdout.
–comments                   Show commented tasks only
–job-stats [LEVEL]          Display job statistics. LEVEL=history displays a complete job list
–rules                      Trace the rules resolution.
–suppress-backtrace PATTERN Suppress backtrace lines matching regexp PATTERN. Ignored if –trace is on.
-A, –all                        Show all tasks, even uncommented ones
-D, –describe [PATTERN]         Describe the tasks (matching optional PATTERN), then exit.
-e, –execute CODE               Execute some Ruby code and exit.
-E, –execute-continue CODE      Execute some Ruby code, then continue with normal task processing.
-f, –rakefile [FILE]            Use FILE as the rakefile.
-G, –no-system, –nosystem      Use standard project Rakefile search paths, ignore system wide rakefiles.
-g, –system                     Using system wide (global) rakefiles (usually ‘~/.rake/*.rake’).
-I, –libdir LIBDIR              Include LIBDIR in the search path for required modules.
-j, –jobs [NUMBER]              Specifies the maximum number of tasks to execute in parallel. (default:2)
-m, –multitask                  Treat all tasks as multitasks.
-n, –dry-run                    Do a dry run without executing actions.
-N, –no-search, –nosearch      Do not search parent directories for the Rakefile.
-P, –prereqs                    Display the tasks and dependencies, then exit.
-p, –execute-print CODE         Execute some Ruby code, print the result, then exit.
-q, –quiet                      Do not log messages to standard output.
-r, –require MODULE             Require MODULE before executing rakefile.
-R, –rakelibdir RAKELIBDIR,     Auto-import any .rake files in RAKELIBDIR. (default is ‘rakelib’)
-s, –silent                     Like –quiet, but also suppresses the ‘in directory’ announcement.
-t, –trace=[OUT]                Turn on invoke/execute tracing, enable full backtrace. OUT can be stderr (default) or stdout.
-T, –tasks [PATTERN]            Display the tasks (matching optional PATTERN) with descriptions, then exit.
-v, –verbose                    Log message to standard output.
-V, –version                    Display the program version.
-W, –where [PATTERN]            Describe the tasks (matching optional PATTERN), then exit.
-X, –no-deprecation-warnings    Disable the deprecation warnings.
-h, -H, –help                   Display this help message.


passing parameter with post method in REST

While making API call, you should avoid passing sensitive information like username, password, social security number etc in the url as anyone can easily read them. The safer way is to make call as post method and pass needed parameter in body. I find this security hole in one of my own code but rectified it before anyone can misuse it.

Below, is the code, which generate authentication token from Openam, which support SSO for my application. Authentication token is needed to perform all task like user creation, deletion etc on Openam. So any person who can get hold of my username and password can getback the authorization token also and hack in Openam

require 'rest_client'
 module Openam
 class Client

   attr_writer :base_url, :username, :password

   def initialize(base_url, username, password)
      @base_url = base_url
      @username = username
      @password = password

   def generate_authorization_token
     uri = "#{@base_url}/authenticate?username=#{@username}&password=#{@password}"
     admin_authorization_token =, 
                                          :content_type => "application/xml")

I have modified, the above generate_authorization_token method to use post method and pass parameter in body instead of url

def generate_authorization_token
   uri = "#{@base_url}/authenticate" # url to which request is made
   payload = {:username=>@username,:password=>@password} # hash containing 
                                                       username and password
   admin_authorization_token =, payload, 
                            :content_type => "x-www-form-url-encoded")
   admin_authorization_token.slice!(9..-1).strip # this step will remove unwanted 
                                           charecter from the token

The main point here is the use of  “x-www-form-url-encoded” as content type which tell REST that url parameter is present in the Body and passing username and password parameter as hash in the payload

1 Comment

check uncheck checkbox jquery

Let we have below checkboxes in our form, and we want to manipulate them through jquery, say counting the number of checkbox checked by user, checking some of them based on some condition and unchecking other based on some other condition and so on …..

=> Sample chekbox in a form

<input type="checkbox" value="confirmation" name="accept_tc" id="accept_tc" checked="checked">
<input type="checkbox" checked="checked" value="Hourly" name="newsletter">
<input type="checkbox" value="Daily" name="newsletter">
<input type="checkbox" value="Weekly" name="newsletter">
<input type="checkbox" checked="" value="Monthly" name="newsletter">
<input type="checkbox" value="Yearly" name="newsletter">

In the above form 3 checkbox will remain selected, you should note that, it will get selected even if  checked=”” i,e if you do not want a checkbox to be selected by default do not use checked attribute for it

=> jQuery Selector for checkbox

jQuery provide :checkbox selector (see here) to return all the checkbox within a form. so below line will return checkbox object.

Object[input#accept_tc confirmation, input Hourly, input Daily, input Weekly, input Monthly, input Yearly]

Similarly, jQuery provide :checked selector (see here) which when chained to :checkbox selector will return, only selected checkbox

Object[input#accept_tc confirmation, input Hourly, input Monthly]

Note: see the difference between the object elements, first checkbox have id accept_tc so returned as input#accept_tc while the other inputs are denoted in different way. It is always good to associate an id with all input element, so that it can be accessed easily on individual level with there id

=> Fetching the detail of each checkbox

Once you have a collection of object, you can iterate over it using .each method of jQuery(see here) , below is the code which iterate over each checkbox element and alert its value, name, and checked or not checked status

$("input:checkbox").each(function(){ # $(this) object represent current element of the loop
alert($(this).val()) # return value of the checkbox
alert($(this).attr('name')) # return name of the checkbox
alert($(this).is(':checked')) # return checked status of the checkbox

=> Checking checked status of checkbox

Once you have the checkbox element you can check whether it is checked or not in the below two ways. $(“input#accept_tc”) is the checkbox with id accept_tc


=> checking a checkbox
It can be done my setting the checked value of a element to be true

$("input#accept_tc").attr('checked', true)

=> unchecking a checkbox
It can be done my setting the checked value of a element to be false

$("input#accept_tc").attr('checked', false)

1 Comment

deploying rails on heroku

Heroku is a cloud application platform – a new way of building and deploying web apps. It take care of all your deployment need like  managing servers, deployment, ongoing operations, and scaling. It is very easy to deploy a rails app on Heroku. Also the steps are well documented here. The document is self sufficient and do not need any other blog on it. But my client raised a jira asking me to document the complete step. Well I can’t post him the link saying it is self explanatory 🙂 .

So here is the documentation I have written.


=> create your HEROKU account

You must have an account on HEROKU. if not sign up here . Remember your credential, you will need them at time of deployment. For me it is as below

email :
password : I will not tell you 🙂

=> Install HEROKU toolbelt

It must be installed on your machine from where you are going to deploy the app on HEROKU. It can be installed with below command on ubuntu.

wget -qO- | sh

For Mac and window you need to download and execute the file available here for window and here for mac.

=> Test your HEROKU login from console

$ heroku login # It will upload your system public key to your heroku account, with below message
Enter your Heroku credentials.
Password (typing will be hidden): **************
Could not find an existing public key.
Would you like to generate one? [Yn]
Generating new SSH public key.
Uploading ssh public key /Users/adam/.ssh/

just press enter, the public key is needed to push your code later on. Here, new public key is created and uploaded to your heroku account. But in my case, you already have the public key, my terminal log look like below.

$ heroku login
Enter your Heroku credentials.
Password (typing will be hidden): **************
Authentication successful.

In this case , since I already have the public key, no new key is generated and key upload step is also skiped, so you should upload the key with the below command otherwise it give error later on while deployment

$ heroku keys:add

=> Install GIT on your system

HEROKU work only with GIT. So it must be installed on your system. on Ubuntu you can install as below. for other OS use the corresponding command.

$ sudo apt-get install git

=> STORE Your Application on git

If you are already using GIT as you source control, you can skip this step.You can add your project to git with below command.

$cd Projects/myfinance # move to your project folder
$ git init
$ git add .
$ git commit -m “initial commit”

STEP 2: Configure Your Application

You have to make only one change to your application before deploying to HEROKU i,e the gem for database in your Gemfile.
NOTE : HEROKU support only pg database, so database in production must be set to pg in the gemfile. By default the Gemfile have below line for database. set by default to sqlit3

gem ‘sqlit3’

You can change above line to gem ‘pg’ or maintain different setting for different environment as below

gem ‘sqlit3’, :group => :development # sqlit3 will be used only in development
gem ‘mysql’, :groups => [:demo, :staging] # mysql will be used in demo and staging
gem ‘pg’, :group => :production # pg gem will be used in production

run bundle install on the terminal
$ bundle install

It will modify the Gemfile and Gemfile.lock,as you can see in git status

$ git status
# On branch master
#    modified:   Gemfile
#    modified:   Gemfile.lock

commit the modified file
$ git commit – a -m”pg gem added for production”

STEP 3: Deploying the Application to HEROKU

=> creating git remote branch on HEROKU

In general case, we have our own remote git repository to which all developer pull and push the code. our project is still not associated with any remote branch as you can see with below comand
$ git remote
origin # only origin i,e your local branch is acting as remote branch also

Add the remote git branch on HEROKU with the below command
$ heroku create
Creating powerful-coast-4672… done, stack is cedar |
Git remote heroku added

You can see that, a remote git branch is added for you on HEROKU. confirm it with below command.
$ git remote
heroku # you have heroku added as your remote git branch

=> Push the code to heroku

Note : If you get Permission denied or other error see this post for solution

$ git push heroku master

Counting objects: 65, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (51/51), done.
Writing objects: 100% (65/65), 26.21 KiB, done.
Total 65 (delta 3), reused 0 (delta 0)

—–> Ruby/Rails app detected
—–> Installing dependencies using Bundler version 1.3.2
Running: bundle install –without development:test –path vendor/bundle –binstubs vendor/bundle/bin –deployment
Fetching gem metadata from……&#8230;
Fetching gem metadata from
Installing rake (10.0.4)
Your bundle is complete! It was installed into ./vendor/bundle
Post-install message from rdoc:
Depending on your version of ruby, you may need to install ruby rdoc/ri data:
<= 1.8.6 : unsupported
= 1.8.7 : gem install rdoc-data; rdoc-data –install
= 1.9.1 : gem install rdoc-data; rdoc-data –install
>= 1.9.2 : nothing to do! Yay!
Cleaning up the bundler cache.
—–> Writing config/database.yml to read from DATABASE_URL
—–> Preparing app for Rails asset pipeline
Running: rake assets:precompile
Asset precompilation completed (16.98s)
—–> Rails plugin injection
Injecting rails_log_stdout
Injecting rails3_serve_static_assets
—–> Discovering process types
Procfile declares types      -> (none)
Default types for Ruby/Rails -> console, rake, web, worker

—–> Compiled slug size: 9.4MB
—–> Launching… done, v6 deployed to Heroku

* [new branch]      master -> master

STEP 4: Starting Your Application

Once you have pushed your code to heroku, you can see in the log above that, it is performing all the regular task like, running the bundle install,

clearing the cache, precompiling the assets etc. Though, you not need to run these command manually, if you want you can do it as below.

1=>heroku run bundle install –deployment # will install all the gems in vendor/bundle folder
2=>heroku run rake db:migrate #  will run all pending migration if any
3=>heroku run bundle exec rake assets:precompile # will precomplie all your assets
4=>heroku restart # will restart the heroku dyno

Recently while deploying my new app on heroku above commands , I found that migration not running on Heroku.

getting below error

heroku[api]: Starting process with command `bundle exec rake db:migrate` by
heroku[run.7050]: Error R13 (Attach error) -> Failed to attach to process
heroku[run.7050]: State changed from up to complete
heroku[run.7050]: Process exited with status 128

It is solved by replacing the command as below i,e running in background following this link.

heroku run:detached rake db:migrate

heroku run:detached rake db:seed


you can run all the command, you use generally use with respect to rake or bundle or anyother rails command by prefixing it with heroku run

We have deployed our code to Heroku in the last step. We can now instruct Heroku to execute a process type. Heroku does this by running the associated command in a dyno – a lightweight container which is the basic unit of composition on Heroku.verify that the dyno running with the below command

$ heroku ps:scale web=1
Scaling web processes… done, now running 1 # so one dyno is running

You can check the state of the app’s dynos. The heroku ps command lists the running dynos of your application:

$ heroku ps
=== web: `bundle exec rails server -p $PORT`
web.1: up 2013/04/18 15:48:12 (~ 44s ago)

So, everything is fine, lets start or open our application with below command

$ heroku open
Opening secret-everglades-4564… done

It will open up your application in the browser with some random url. For me it is

If you go to your HEROKU account, you can see all your deployed application on the dashboard, click any of them and other settings you will find all the details like git url, application url etc.

Till now we have not associated any domain name to our application, so it will be accessible with the url :

We will map the above url to proper url say in the next step

STEP 5: Assiging proper url to Application
Let say we have purchased, a domain name for our application. We want that our application should be accessible at URL rather then

coming soon…..

Leave a comment

fatal: The remote end hung up unexpectedly in heroku

I have explained deploying rails app on heroku in this post. I get into below error while trying to push the code on HEROKU.

$ git push heroku master # command to push code to heroku, got below error message on console
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

From the message, we can see that, there is some problem with the publickey. public key of your system should be present in your HEROKU account.

This key get added when you try to login to heroku from you development machine for the first time as below
$ heroku login
Enter your Heroku credentials.
Password (typing will be hidden): **************
Could not find an existing public key.
Would you like to generate one? [Yn]
Generating new SSH public key.
Uploading ssh public key /Users/adam/.ssh/

just press enter, the public key is needed to push your code later on. Here, new public key is created and uploaded to your heroku account. But in my case, since my system already have the public key, my terminal log look like below.

$ heroku login
Enter your Heroku credentials.
Password (typing will be hidden): **************
Authentication successful.

PEOBLEM : In my case , since I already have the public key, but is not uploaded to my HEROKU account, so Iam getting the above error

SOLUTION : upload your public key to your HEROKU account

It can be done with below command:
$ heroku keys:add # it will upload your key as you can see in the terminal message
Found existing public key: /home/arun/.ssh/
Uploading SSH public key /home/arun/.ssh/… done

If you are not aware of certain HEROKU command you can get the detail with below step. Infact, I do not know myself the command to add the keys but get it with the below steps.

$ heroku # it will list all availabe command
Usage: heroku COMMAND [–app APP] [command-specific-options]

Primary help topics, type “heroku help TOPIC” for more details:

  addons    #  manage addon resources
  apps      #  manage apps (create, destroy)
  auth      #  authentication (login, logout)
  config    #  manage app config vars
  domains   #  manage custom domains
  logs      #  display logs for an app
  ps        #  manage processes (dynos, workers)
  releases  #  manage app releases
  run       #  run one-off commands (console, rake)
  sharing   #  manage collaborators on an app

Additional topics:

  account      #  manage heroku account options
  certs        #  manage ssl endpoints for an app
  db           #  manage the database for an app
  drains       #  display syslog drains for an app
  fork         #  clone an existing app
  git          #  manage git for apps
  help         #  list commands and display help
  keys         #  manage authentication keys
  labs         #  manage optional features
  maintenance  #  manage maintenance mode for an app
  pg           #  manage heroku-postgresql databases
  pgbackups    #  manage backups of heroku postgresql databases
  plugins      #  manage plugins to the heroku gem
  stack        #  manage the stack for an app
  status       #  check status of heroku platform
  update       #  update the heroku client
  version      #  display version
Now to know about any of the command say key we can get further detail as below with –help option:

$ heroku keys –help # it will tell you all options available for keys and how to use them
Usage: heroku keys

display keys for the current user

 -l, –long  # display extended information for each key

Additional commands, type “heroku help COMMAND” for more details:

keys:add [KEY]   #  add a key for the current user
  keys:clear       #  remove all authentication keys from the current user
keys:remove KEY  #  remove a key from the current user

Leave a comment

jquery utilities class

Recently, I need to remove trailing and leading white space from password if entered by user unknowingly . I have did it earlier but forget the name of the function. Well it is the trim function to do the work. But good thing is that, searching for it this time I come to know that, trim belong to jquery utilities class and it have a number of other helpful function within it. I decided to maintain this post and keep adding, the different function here, whenever I get chance to use them in my code. You can find the detail of this class here

=> trim()

Description: Remove leading and trailing spaces

The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these white space characters occur in the middle of the string, they are preserved. detail available here


Let we have a form to reset password as below, with password and confirm_password input fields and a submit button

<form method="post" id="update-password">
  <input type="password" name="user[password]" id="user_password" />
  <input type="password" name="user[password_confirmation]" id="user_password_confirmation" />
  <input type="submit" value="Update" name="commit" class="btn btn-primary password_reset" />

Now, the jquery code is as below. On click of submit button, we will collect the password and confirm_password value, apply trim() function to it and reinsert the value again

      var password = $("#user_password").val().trim()
      var confirm_password = $("#user_password_confirmation").val().trim()

=> data()

This method allow you to add arbitrary data to any DOM element on fly or read the different data elements associated with a DOM element. The detail documentation is available here


.data(“key”, “value”) # will attach data attribute key set to value

.data(“key”) # will return data hold by key

Example 1: Reading data attribute from form input or anyother DOM element

Adding data element to form input. Let our password reset form need some additional functionality, say if the user has already change the password, he should not be allowed to change it again, also we need user id or email etc in our jquery validation when the submit button is click. So in this case we can pass these values to data attribute of our button or password input filed or any other DOM element within the form. let pass it to password input. So Now our form will look  like as below

<form method="post" id="update-password">
  <input type="password" name="user[password]" id="user_password" />
  <input type="password" name="user[password_confirmation]" id="user_password_confirmation" 
   data-reset_already="yes" data-user_id="235" date-email="" />
  <input type="submit" value="Update" name="commit" class="btn btn-primary password_reset" />

If you are from ruby background, you can add data attribut to input elemnt with ruby syntex as below. assuming that your user object contain all the value i,e email, password_status etc, the bold line above will look as below and will generate exactly same input as above bolded input

<%= f.password_field :password, 'data-already_reset' => @user.password_status, 
'data-user_id' =>, 'data-email' => %>

Now, you can retrieve all these data value in the jQuery code as below:

      var status = $("#user_password").data('reset_already') #like data attached to password
               input filed here you can attach it to any element like <div> <p> <tr> etc
      var user_id = $("#user_password").data('user_id')
      var email = $("#user_password").data('email')
      alert(status) # I have just alerted the value, you can use it in any of your logic

Example 2: Attaching data to DOM element.

In previous example, the data attribute is added to the input element and retrieved in our jQuery function. Here we will add data attribute to DOM element on fly from our jquery code. I have inspected the element to which the code below add the test data , but do not find it added there as we have added in example one i,e I do not find any data-test=”Yes”, but on retrieving and alerting the data(“test”) it return the correct value. May be it has to do something with below description of data method in jQuery documentation, which is not very clear to me.

The method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page

   var getelemnt = $("#user_password");'test', "No")

=> each()

It is iterator method which it iterate over collection of object, Array or Hash in jQuery. detail is available here .

Example :

Below code iterate over all the checkbox within a page and alert its value name and checked status.

$("input:checkbox").each(function(){ # $(this) object represent current element of the loop
alert($(this).val()) # return value of the checkbox
alert($(this).attr('name')) # return name of the checkbox
alert($(this).is(':checked')) # return checked status of the checkbox