Tuesday 24 June 2014

MONGO DB BASICS FOR BEGINNERS


Mapping RDBMS TO MongoDB:

RDBMSMongoDB
DatabaseDatabase
TableCollection
Tuple/RowDocument
columnField
Table JoinEmbedded Documents
Primary KeyPrimary Key (Default key _id provided by mongodb itself)
Database Server and Client
Mysqld/Oraclemongod
mysql/sqlplusmongo

Basic Queries:

Use database:
>use [database_name] #create and switch to that database
Ex: >use mongo
#switch to mongo database

show collections:
>show collections #To show collections in mongo database.

Current Database:
>db #To show current database

To show Databases:
>show dbs #To show all databases
Note: Its not displaying sari database because there is no data in sari database. first insert some records in database.

Drop Database:
>db.dropdatabase()#To drop a current database

Select Records:
>db.collectionName.findOne()
#To show first record in a collection
>db.collectionName.find().pretty
#To show all fields in a format
>db.collectionName.find().limit(5)
>db.collectionName.find( { _id: 5 } )
#displays records with id=5
>db.collection.find( { field: { $gt: value1, $lt: value2 } } );
Ex:>db.students.find( { score: { $gt: 0, $lt: 2 } } )
#To specify ranges
Create a Collection:
>db.createCollection(nameoptions)
#To create a collection
Ex: db.createCollection(student, {name: <string>, qual: <string>, age: <number>})

Insert Values Into Collection:

>db.collectionname.insert( { field1: value1, field2: val2} )
Ex:db.students.insert( { name: "ss", qual: "btech", age: 15 } )

To Remove Specific Documents:
>db.collection.remove()
#to delete a document in collection
Ex:>db.students.remove( { age: { $gt: 20 } } )






Monday 23 June 2014

How do I create a MongoDB dump/Restore of my database?



To DAMP SPECIFIC DATABASE

Syn: $mongodump --db [database name]
Ex:   $mongodump --db mongo

I t wil create a dumb file in home/dump folder with the name of mongo

The --out option allows you to specify the directory where mongodump will save the backup.mongodump creates a separate backup directory for each of the backed up databases

Syn: $mongodump --db [database name] --out [dumb foldername]
Ex:   $mongodump --db mongo --out saritha

I t wil create a backup files in saritha/dump folder with the name of mongo

To dump specific collection in database:
Syn: $mongodump --db [database name] --collection [collection name]
Ex: $mongodump --db mongo --collection users

To zip the dump file:

Syn: $mongodump -db [dtabasename] --collection [collection name] --out - | gzip > [zip file name].gz

Ex: $mongodump -db mongo --collection users --out - | gzip > mongo1.gz

CHeck it in your home folder with name mongo1.gz

[or] With a date in the filename:

Syn: $mongodump -db [database name] --collection [collection name] --out - | gzip > dump_`date "+%Y-%m-%d"`.gz


TO RESTORE DATABASE


Syn:$mongorestore [database name with path]/

Ex:$mongorestore mongo/

Syn:
$ mongorestore --drop -d <database-name> <directory-of-dumped-backup>

--drop:
The restoration procedure will drop every collection from the target database before restoring the data from the dumped backup.

-d <database-name>:

To specify the database name.


Wednesday 18 June 2014

HOW TO LOAD TWITTER BOOTSTRAP LESS FILES


step 1:Add

gem 'less-rails'

to your Gemfile

step 2:  Add bootstrap bootstrap_override.css.less file in your style sheets folder.

import .less files in bootstrap_override.css.less 

Example: /stylesheets/bootstrap_override.css.less 

@import "/twitter/bootstrap/less/bootstrap.less";
@import "/vars/variables.less";

@import "04-variables.less";

add <%= stylesheet_link_tag :bootstrap_override %>


Now it will works fine.............



@@@@@@@@@@@@Happy Rails Coding @@@@@@@@@@@@@@@






Monday 16 June 2014

Best way to get the multiple checkbox checked value using JQuery

Multiple check box checked value using JQuery


<div class="panel-body" id="checkboxlist">
   <p><input name="sort" type="checkbox" value="$0-$149" class="search" > $0 - $149</p>
   <p><input name="sort" type="checkbox" value="$150-$499" class="search"> $150 - $499</p>
   <p><input name="sort" type="checkbox" value="$500-$1499" class="search"> $500 - $1499</p>
   <p><input name="sort" type="checkbox" value="$1500-$2499" class="search"> $1500 - $2499</p>
   <p><input name="sort" type="checkbox" value="$2500Up" class="search"> $2500 And Up</p>
 </div>

Then add script:

<script>
$(".panel-body").on("change", "[type=checkbox]", function () {
    var s = "";
    $(".panel-body [type=checkbox]:checked").each(function () {
        s += this.value + ",";
    });
    alert(s.slice(0, s.length - 1));
    
});
</script>

{OR}

<script>
$(".panel-body").on("change", "[type=checkbox]", function () {
    alert("hello");
    var s = "";
    $(".panel-body [type=checkbox]:checked").each(function () {
        s += (s == '') ? this.value : "," + this.value;
    });
    alert(s);
   
});
</script>

Everytime a change happens in the text box, each event gets the values of checked checkboxes and adds them to the div.

 *************AWESOME J QUERY***********

Sunday 15 June 2014

Pagination In Rails4 Using 'will_paginate' Gem

Pagination In Rails4 Using 'will_paginate' Gem:


1, add below line to Gemfile
gem 'will_paginate'
2, Run bundler
$bundle install
3, Add below line to your method in controller.
#to define per_page value
@products=@category.products.all.paginate(:page => params[:page], :per_page => 10)
4, Add below code to related html.erb file.
<%= will_paginate @products %>
#It will display only simple links, Inorder to apply different styles to pagination download pagination.css and pagination.sass from http://mislav.uniqpath.com/will_paginate/
5, keep that two files in app/assets folder.
6, Add below two lines to application.html.erb (i.e, your layout).
<%= stylesheet_link_tag :pagination %>
<%= stylesheet_link_tag “pagination.sass” %>
7, Add related css class to your pagination tag in related view file.
<div class="digg_pagination" align="right"><%= will_paginate @products %></div>
Here we have three different types of pagination classes they are specified in paginate.css files:
  • digg_pagination
  • apple_pagination
  • flickr_pagination
we can use thouse classes according to our requirement.

Happy Rails Coding................

Wednesday 11 June 2014

HOW TO CHANGE PASSWORD FOR UBUNTU SYSTEM

$ passwd
Changing password for ramesh.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

HOW TO GENERATE ER-DIAGRAMS IN RAILS 4


ER -DIAGRAMS IN RAILS4


Entity relationship diagrams are a great way to quickly visualize the structure of a Rails database & project.
In this post, we'll get up and running with the rails-erd gem which will allow us to quickly generate ERD diagrams. After that, we'll set up a rake task so that everyone on the project uses the same command to generate the diagrams. Finally, we'll show off the diagram in the readme of our Github Project!

STEP 1: Install Graphviz (Rails ERD requires Graphviz.)

$sudo apt-get install graphviz

STEP 2:Add ‘rails-erd’ gem to your existing app’s Gemfile

gem 'rails-erd'

STEP 3:Run bundle command

$bundle

STEP 4: Open your app console and run the below command.

[app path]$bundle exec rake erd filetype=pdf

[OR]

[app path]$ bundle exec rake erd filetype=dot

Now go to your application root directory, you will get there erd.pdf or erd.dot file.


@@@@@@@HAPPY RAILS CODING@@@@@@



Tuesday 10 June 2014

MONGODB INSTALLATION ON UBUNTU

MONGODB INSTALLATION ON UBUNTU OS


Step 1: The Ubuntu package management tool (i.e. dpkg and apt) ensure package consistency and authenticity by requiring that distributors sign packages with GPG keys.

$sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10



Step 2: Create mongodb source list.

$echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list



Step 3: Reload your Repository.
$sudo apt-get update



Step 4:Install mongodb pakages.

$sudo apt-get install mongodb-10gen



Step 5: Test new mongodb.
Let's try  to Start, Stop and Restart MongoDB 



 You can see in the image above, after installation process is finished, it's start mongoDb automatically.  If not, you should use the command : sudo service mongodb start  to start it up.
We also have the command: sudo service mongodb stop  and sudo service mongodb restart  to stop and start it.

 Testing mogodb on mongo shell 

  - To ensure mongodb works well, try some basic command to save new data and find them on mongo shell.
 - To use mongodb on mongo shell, just type : mongo on terminal.
    + To add new data  into mongodb try : db.test.save ({codingtip : 1})
    + To see all data in database , try : db.test.find() 
with db.test is Test database which is auto created by mongodb in installations




Wednesday 4 June 2014

USER DEFINED FORMS AND FORM ELEMENTS ACCESSING

USER DEFINED FORMS AND ACCESS FORM ELEMENTS



In my Pages controller--->home.html.erb

I am creating another user defined form in home.html.erb:

    <%= form_tag( { :controller=>"newsletters", :action => :create, }, { :method => :post })  %>
                        <%= text_field_tag 'name','',:placeholder =>"Your FullName" %>
                        <%= text_field_tag 'email','',:placeholder => "Email Address" %>
    <%=submit_tag 'SUBMIT', :class=>"button-type1"%>

The controller goes to newsletters/create method.

newsletters_controller.rb

 def create
    @newsletter = Newsletter.new
#Accessing user defined elements in newsletter_controller.rb
    @newsletter.name=params[:name].to_s
    @newsletter.email=params[:email].to_s
    if @newsletter.save
# email sending statement
       NewsletterMailer.newsletter_confirmation(@newsletter).deliver
#For redirection to root path
       redirect_to :root, notice: 'Confirmation Mail Sent to Your Mail.'
    else
      render action: 'new'
    end

  end

Tuesday 3 June 2014

EMAIL SENDING IN RAILS...


SMTP CONNECTION IN RAILS



Step 1: Here smtp connection for newsletter.

$rails g scaffold newsletter name:string email:string



Step 2: Migration


$rake db:migrate


Step 3: To generate mailer related files for newsletter

$rails g mailer newsletter_mailer


Step 4:Run bundle command


$bundle install


Step 5:Create a new file in /config/initializers/setup_mail.rb


ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "saritha.chakilala41@gmail.com",
:password => ".........",
:authentication => "plain",
:enable_starttls_auto => true
}

ActionMailer::Base.default_url_options[:host] = "localhost:3000"


Step 6: Write below lines of code in app/mailers.newsletter_mailer.rb


class NewsletterMailer < ActionMailer::Base

    default from: "saritha.chakilala41@gmail.com"
#To send email to multiple  recipients
    default to: Proc.new { Newsletter.pluck(:email) }
    def daily
        mail(:subject => "TESTING MAIL")
    end 

end


Step 7: Create and Write your mailing related text in /app/views/newsletter_mailer/daily.html.erb

I write some text here...

 <html>
    <body>
        <h1><font color="red">Hello Every One...There is one new product...lets try </font></h1>
    </body>
</html>

Step 8: Run the below command on rails console

NewsletterMailer.daily.deliver



SOURCE FROM:http://asciicasts.com/episodes/206-action-mailer-in-rails-3


@@@@@@@HAPPY RAILS CODING@@@@@@

Monday 2 June 2014

AJAX WITH JQUERY RAILS

AJAX WITH JQUERY RAILS

 routes.rb (i defined a customized method)

 get 'products' => 'products#reviews_lists', :as => 'reviews_lists'
 
in my root page: i.e,

show.html.erb
<%= javascript_include_tag "jquery-1.7.1.min" %>
<script type="text/javascript">
 jQuery(document).ready(function() {
    alert("saritha ");
    $('#review_list').change(function() {
        alert($('#review_list :selected').text());
        $.ajax({
              url: "<%= reviews_lists_path %>",
            data: {

              reviw_name : $('#review_list :selected').text(),
              pid: $('#pid').val(),

            },
            dataType: "script"
      });
    });
});
</script>

 <p>
  <%= select_tag :sort, options_for_select([["Newest  First",1],["1-5",2],["5-10",3]]), { :prompt => 'please select',:id=>"review_list", :pid=>'#{ @product.id}' }%>
   </p>
  <div id="saritha" class="review"> .... </div>

products_controller.rb

def reviews_lists
  @review_limit=params[:reviw_name].split('-')
    @reviews=Review.where("pid = ?", params[:pid]).order(:created_at).limit(@review_limit[1])
    respond_to do |format|
       format.js
    end
  end

reviews_list.js.erb

$('#saritha').html("<%= escape_javascript(render(:partial => 'show_review', :locals => {:reviews => @reviews})) %>");


 show_review.html.erb

<div class="clear"></div>
<% reviews.each do |review| %>
<div class="review">
       <p><strong><%= review.review_title %></strong></p>      
        <p><%= review.opinion %>.</p>
        <p>By <span><%= review.name %></span><br>from <%= review.location %> </p>
        <div class="review-bot">
            <p class="report"><a href="#">Report this comment</a></p>
            <p class="help">Was this review helpful?  <a href="#">Yes  /</a>  <a href="#">No</a></p>
        </div>
  </div>
 <% end %>





@@@@HAPPY RAILS CODING....