Month: April 2015

Simple CRUD operations with file upload ruby on rails

The controller file

class WelcomeController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  def index
  def list
  	@tweets = Tweet.all
  def save

	upload = params[:upload]
        name =  upload['datafile'].original_filename
	directory = "public/tweet_files"
	# create the file path
	path = File.join(directory, name)
        # write the file, "wb") { |f| f.write(upload['datafile'].read) }

  	t =
	t.title = params[:title]
	t.tweet = params[:tweet]
	t.file = name

        flash[:notice] = "Tweet saved!"
        redirect_to :action => 'list'
  def new
  def edit
       @tweet = Tweet.find(params[:id])
  def delete
       t = Tweet.find(params[:id])
       flash.keep[:notice] = "Tweet deleted!"
       redirect_to :action => 'list'
 def update
	upload = params[:upload]
        name =  upload['datafile'].original_filename
	directory = "public/tweet_files"
	# create the file path
	path = File.join(directory, name)
        # write the file, "wb") { |f| f.write(upload['datafile'].read) }

       t = Tweet.find(params[:id])
       t.title = params[:title]
       t.tweet = params[:tweet]
       t.file = name
       flash.keep[:notice] = "Tweet updated!"
       redirect_to :action => 'list'

view files list.html.erb

border-collapse: collapse;
    font-family: "Trebuchet MS",Arial,Helvetica,sans-serif;
    width: 100%;
table, td, th {
    border: 1px solid green;

th {
    background-color: green;
    color: white;
<%= notice %><br>
<%= link_to "Add new",:controller => :welcome, :action => :new %>
<% @tweets.each do |tweet| %>
 <td><%=  tweet.title %></td>
 <td><%=  tweet.tweet %></td>
<td><%=  image_tag("/tweet_files/#{tweet.file}") %></td>
<td><%= link_to "Edit",:controller => :welcome, :action => :edit ,:id => %> </td>
<td><%= link_to "Delete",:controller => :welcome, :action => :delete,:id =>  %> </td>
<% end %>
<% if @tweets.size == 0 %>
<em>No tweets found</em>
<% end %>


<%= form_tag({controller: "welcome", action: "update"}, method: "post",multipart: true) do %>
  <%= label_tag(:tweet, "Update Tweet") %>
  <%= text_field_tag "title" , @tweet.title %> 
  <%= text_field_tag "tweet" , @tweet.tweet %>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
<%=  image_tag("/tweet_files/#{@tweet.file}") %>
  <%= submit_tag("update") %>
<% end %>


<%= form_tag({controller: "welcome", action: "save"}, method: "post",multipart: true) do %>
  <%= label_tag(:tweet, "Add Tweet") %>
  <%= text_field_tag "title" %>
  <%= text_field_tag "tweet" %>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
  <%= submit_tag("Save") %>
<% end %>


   root 'welcome#list'
   post 'welcome/save' => 'welcome#save'
   get  'welcome/new'  => 'welcome#new'
   get  'welcome/edit/:id'  => 'welcome#edit'
   get  'welcome/delete/:id'  => 'welcome#delete'
   post  'welcome/update/:id'  => 'welcome#update'

Here is how to add migrations to active records…adding column file here

$ rails generate migration add_file_to_tweets file:string
$ rake db:migrate

Here is how to create folder

cd myrailsproject
cd public
mkdir tweet_files

Setting up an application with mysql database on rails server on ubuntu 14.04

Simple steps to be followed
I assume you have installed rails, ruby gems and mysql

1) Create a new application with mysql database.

— name of application : myapplication
— db driver mysql

	$ rails new myapplication -d mysql

2) Run your application on rails server

CD to myapplication

	$ rails server

3) Create a database for the application
CD to myapplication

	$ rails db

Enter the password for root user

	mysql> create database mydb;
	mysql> create user abc identified by 'PASSWORD';
	mysql> grant all privileges on mydb.* to abc@localhost identified by 'PASSWORD';

4) Now place the username,password and database name in database.yml file under config folder of your app.
5) Goto routes.rb
— uncomment root ‘welcome#index’

6) Create a controller class welcome_controller.rb under controller folder and add an action index to it.

	class WelcomeController < ApplicationController
		def index

7) Create a view file for function index under views/welcome/index.html.erb

<h1>Hello Rails</h1>

to view file.
8) Now run the rails server as
CD to myapplication

   $ rails server

open in browser —> localhost:3000

You will see Hello Rails in browser window.

Upload image plus all form data using jquery


<form action="" method="post" enctype="multipart/form-data" id="form_portfolio_save">
				<input type="text" name="title" id="title" placeholder=""/><br/>
				<textarea id="about_project" name="about_project">About project</textarea><br/>
				<input type="file" name="photo" id="port_image" placeholder="Add Files"/><br/>
				<input type="text" name="caption" id="caption" placeholder="Image caption"/><br/>
				<input type="button" id="submit" value="Submit" class="button submit" onclick="save_portfolio();return false;"/>
				<input type="button" class="button cancel" id="submit" value="Cancel" />


function save_portfolio(){
		var fd = new FormData();
		var file_data = $('input[name^="photo"]')[0].files; 
		for(var i = 0;i<file_data.length;i++){
			fd.append("file_"+i, file_data[i]);
		var  other_data = $("#form_portfolio_save").serializeArray();
		url : 'save_portfolio.php',
		type : "post",
		data : fd,
		cache: false,
		contentType: false,
		processData: false,
		success : function(data){


		$filename = time().$_FILES['file_0']['name'];
		$path= "upload/user_portfolio/".$filename;
$query = "insert into user_portfolio(title,description,images,image_captions,employee_id) values('".$_POST['title']."','".$_POST['about_project']."','".$filename."','".$_POST['caption']."','".$_SESSION['user_details']['id']."')";


To use PDT, you must activate PDT and Auto Return in your PayPal account profile. You must also acquire a PDT identity token, which is used in all PDT communication you send to PayPal.

Follow these steps to configure your account for PDT:

1)Log in to your PayPal account.
2)Click the Profile subtab.
3)Click the My Selling Tools button in the left column.
4)Find the Selling online section and click Update in the Website preferences row.
5)Under Auto Return for Website Payments, click the On radio button.
6)For the Return URL, enter the URL on your site that will receive the transaction ID posted by PayPal after a customer payment.
7)Under Payment Data Transfer, click the On radio button.
8)Click Save.
9)Find the Selling online section and click Update in the Website preferences row again.
10)Scroll down to the Payment Data Transfer section of the page and take note of your PDT identity token.

Create the form now with notify url and cancel url

<form action="" method="post" accept-charset="utf-8"> 
    <input type="hidden" name="cmd" value="_xclick" /> 
    <input type="hidden" name="charset" value="utf-8" /> 
    <input type="hidden" name="business" value="" /> 
    <input type="hidden" name="item_name" value="Stuffed bear" />
    <input type="hidden" name="item_number" value="BEAR05" />
    <input type="hidden" name="amount" value="20.00" />
    <input type="hidden" name="currency_code" value="USD" />
    <input type="hidden" name="return" value="" /> 
    <input type="hidden" name="cancel_return" value="" />
    <input type="hidden" name="bn" value="Business_BuyNow_WPS_SE" /> 
    <input type="image" src="" name="submit" alt="Buy Now" />

Catch the return now as $_GET[‘tx’] and repost to paypal

  $tx = $_GET['tx'];
  $request = curl_init();
  curl_setopt_array($request, array
  CURLOPT_URL => '',
  CURLOPT_POSTFIELDS => http_build_query(array
      'cmd' => '_notify-synch',
      'tx' => $tx,
      'at' => $your_pdt_identity_token,
  // CURLOPT_CAINFO => 'cacert.pem',

// Execute request and get response and status code
$response = curl_exec($request);
$status   = curl_getinfo($request, CURLINFO_HTTP_CODE);
if($status == 200 AND strpos($response, 'SUCCESS') === 0)
    // Further processing
    // Log the error, ignore it, whatever 
// Close connection

Add custom marker to Google map

<script src=""></script>	<!-- Google Maps API -->
	var map;	// Google map object
	// Initialize and display a google map
	function Init()
		// Create a Google coordinate object for where to center the map
		var latlngDC = new google.maps.LatLng( 38.8951, -77.0367 );	// Coordinates of Washington, DC (area centroid)
		// Map options for how to display the Google map
		var mapOptions = { zoom: 12, center: latlngDC  };
		// Show the Google map in the div with the attribute id 'map-canvas'.
		map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
		// Place a standard Google Marker at the same location as the map center (Washington, DC)
		// When you hover over the marker, it will display the title
		var marker = new google.maps.Marker( { 
			position: latlngDC,     
			map: map,      
			title: 'Washington, DC',
			icon : 'bigcity.png',					// image to display as the marker
			animation: google.maps.Animation.BOUNCE	// set marker to bounce
	// Call the method 'Init()' to display the google map when the web page is displayed ( load event )
	google.maps.event.addDomListener( window, 'load', Init );

	/* style settings for Google map */
		width : 500px; 	/* map width */
		height: 500px;	/* map height */
	<!-- Dislay Google map here -->
	<div id='map-canvas' ></div>

Time Ago function

function time_ago($date)


				if(empty($date)) {

							return "No date provided";


				$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");

				$lengths = array("60","60","24","7","4.35","12","10");

				$now = time();

				$unix_date = strtotime($date);

				// check validity of date

				if(empty($unix_date)) {

						return "Bad date";


				// is it future date or past date

				if($now > $unix_date) {

						$difference = $now - $unix_date;

						$tense = "ago";

				} else {

						$difference = $unix_date - $now;
						$tense = "from now";}

						for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {

						$difference /= $lengths[$j];


				$difference = round($difference);

				if($difference != 1) {

						$periods[$j].= "s";


						return "$difference $periods[$j] {$tense}";


Pass variable to TCPDF class header or any class function

class MYPDF extends TCPDF {
	public $template;
	public function setData($template){
    $this->template = $template;
	public function Header() {
        // get the current page break margin
        $bMargin = $this->getBreakMargin();
        // get current auto-page-break mode
        $auto_page_break = $this->AutoPageBreak;
        // disable auto-page-break
        $this->SetAutoPageBreak(false, 0);
        // set bacground image
        $img_file = "uploads/template_background_image/".$this->template.".png";
        $this->Image($img_file,0, 100, 390, 397, '', '', '', false, 300, '', false, false, 0);
        // restore auto-page-break status
        $this->SetAutoPageBreak($auto_page_break, $bMargin);
        // set the starting point for the page content

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, array(400,500), true, 'UTF-8', false);