Become web developer using Ruby on Rails

If you are a newbie to programming and want to become web developer means the best place is to start with Ruby on Rails shortly called as (ROR), Ruby is easy to learn language and ROR is fully configured frame work so you can directly work with your first database backed website with in a days.

In this article, I will give you idea about where you to start and end. There are four steps involved in web development they are.

  • Getting knowledge in basic things like HTML,CSS,JS
  • Familiar with databases and database queries
  • Basics of ruby
  • Learning ROR
  • Going deep with ROR

 

  1. Basics

In my opinion he best place to familiar with HTML,CSS and JS is w3schools or tutorials point. Both have interactive tutorials so you can run your code directly on the browser, and they don’t charge for any tutorial.

HTML –       https://www.w3schools.com/html/

https://www.tutorialspoint.com/html/

CSS –            https://www.w3schools.com/css/default.asp

https://www.tutorialspoint.com/css/

JavaScript – https://www.w3schools.com/js/default.asp

https://www.tutorialspoint.com/javascript/

2. Databases

Once you complete this you will familiar with how static websites are working, now it is the time to move with dynamic websites for this we have to study about databases. At first study about databases little bit and work with SQL databases (Later you may move to any database you wish).

For this also go with tutorials point, in Rails we don’t directly write database queries it is enough to understand basics of SQL and queries (for now).

SQL – https://www.tutorialspoint.com/sql/index.htm

3. Ruby

There are lot of ruby tutorials available in web, I will give you some quick way to learn ruby. Which will take minimal time and you can most of ruby syntax.

  1.  Ruby in 20 minutes https://www.ruby-lang.org/en/documentation/quickstart/
  2. Study Little book of ruby (Even though this book is older it is enough for understanding basic syntax of ruby) http://www.sapphiresteel.com/IMG/pdf/LittleBookOfRuby.pdf
  3. If you time and wish to learn ruby more try with this free tutorial https://www.codeschool.com/courses/try-ruby (Other ruby course in codeschool will ask you money)

This will give you basic ideas about ruby language.

 

4. Ruby on Rails

For beginner I will suggest only two websites to learn ruby on rails

  1. https://www.railstutorial.org/book/beginning

This tutorial not only covers ruby on rails. It will cover many tools like git, testing, hosting application on heroku. For the first time, you feel difficulties. But finish this tutorials so that you will familiar not only with ROR and also with code versioning, testing, deployment.

2. https://www.theodinproject.com/home

This is open source project, Covers most of the things including html,CSS, JS, Ruby, ROR.

5. Deep with ROR

Now you know how to create ROR application and work with that app.  Now it is the time to learn more things on ROR. I will give you some of the places where it is useful to spend time.

  1. Ruby Guides http://guides.rubyonrails.org/
  2. http://railsforzombies.org/
  3. http://tutorials.jumpstartlab.com/projects/blogger.html
  4. http://railscasts.com/

 

 

Advertisements

Ruby on Rails application Deploying in Heroku

Deploying ROR application in heroku is not a rocket science  now but some developer is having some confusion with this thing so only this blog post , So this post not for experienced developers 🙂

The first thing you need to understand heroku uses git for deployment , so that you need to have git repository in your ROR application first .

Then you need to install heroku toolbelt go here to get tool-belt for your OS , then install heroku gem

gem install heroku

If you don’t have heroku account create one https://id.heroku.com/login, then on your terminal type

heroku login

It will asks your credentials give them, then go to your application directory by terminal and type

heroku create optional-app-name

If you give application name it will create DNS same like that otherwise it will generate one for you.Then type

git push heroku master

It will push your code to heroku , It uses SSH to access , This is first time in your system to connect with heroku and using SSH means , type

ssh-keygen -t rsa

heroku keys:add

note: Heroku uses pg as default data base, so please ensure you have included gem ‘pg’ in your gem file.

If you have any problem with ssh see https://devcenter.heroku.com/articles/keys

Multiple model search in rails with solr

lrSearching is much easier if you use solr or elastic search, no need to write complex database queries.

If you want to integrate solr with your rails application means there is a gem available https://github.com/sunspot/sunspot

Add to Gemfile:

gem 'sunspot_rails'
gem 'sunspot_solr' # optional pre-packaged Solr distribution for use in development

Bundle it!

bundle install

Generate a default configuration file:

rails generate sunspot_rails:install

If sunspot_solr was installed, start the packaged Solr distribution with:

 bundle exec rake sunspot:solr:start

Then add the following code in model file which you going to search

searchable do
  text :<field_name>
end

In your controller queries

@search = Project.solr_search do
fulltext params[:search]
end
@projects = @search.results

Thats all, if you pass search params from your view file, then solr will give you the relevant projects.

Now I will show you how to search multi models in same querie,

simply add the same

searchable do
 text :<field_name>
end

In model files which you need to search, Then in your controller

@search = Sunspot.search(Project,Comment, File) do |s|
 s.fulltext(params[:search])
end

@result = @search.result

will give you the result from project, file and comment models


					

Run Sinatra along with Rails

Sinatra is much better than rails for writing API codes and small functionalities, We can run sinatra app inside rails application.

Write your sinatra codes inside library folder of rails application, you can call rails application database tables from sinatra app also.

Then on your rails app config.ru

# This file is used by Rack-based servers to start the application.

require ::File.expand_path(‘../config/environment’, __FILE__)

require_relative ‘lib/api’

map ‘/api’ do
run API::SinatraApp.new
end

map ‘/’ do
run Rails.application
end

Put this code, so normal request goes to rails controller and  request url with /api goes to sinatra app. This way we can use both rails app and sinatra app together.

 

My new gem – label_better_rails

Hi after a success of my previous gem sticky-rails ( gemmified version of sticky jquery plug-in)  , I have created another gem and this also a gemmified version of another beautiful jquery plug-in label_better ,
This will help you to add label_better gem to your rails application assets pipeline quickly , Home page for this gem is https://github.com/navinspm/label_better_rails

Thanks to http://www.thepetedesign.com/demos/label_better_demo.html

Label your form input like a boss with beautiful animation and without taking up space

Screen shot

Installation

Add this line to your application’s Gemfile:

gem 'label_better_rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install label_better_rails

label_better is a jquery_plug in that gives beautiful animation to your label , so please check if you are using the jquery on your rails app, and add jquery.label_better in your application.js

Your app/assets/javascripts/application.js appear like:

//= require jquery
//= require jquery_ujs
//= require jquery.label_better
//= require_tree .

Then in your view file where you want to add label_better just remove our default rails label then give a class name and the placeholder to the field example

    <%= f.text_field :firstname ,:class => 'label_better', :placeholder => 'firstname'%><br/><br/>
    <%= f.text_field :lastname ,:class => 'label_better', :placeholder => 'lastname'%><br/><br/>
    <%= f.email_field :email,:class => 'label_better', :placeholder => 'email' %><br/><br/>
    <%= f.phone_field :phonenumber,:class => 'label_better', :placeholder => 'Mobile' %><br/><br/>
    <%= f.url_field :website ,:class => 'label_better', :placeholder => 'Website'%><br/><br/>
    <%= f.password_field :password ,:class => 'label_better', :placeholder => 'confirmpassword'%><br/><br/>
    <%= f.password_field :confirmpassword , :class => 'label_better', :placeholder => 'confirmpassword' %>

then add javascript in your view file

$("input.label_better").label_better({
    position: "top", 
    animationTime: 500, 
    easing: "ease-in-out",
    offset: 5, 
    hidePlaceholderOnFocus: true 
  });

Change this values depends on your need

Contributing

  1. Fork it ( https://github.com/[my-github-username]/label_better_rails/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Collection Of Database Queries in Rails

Retrieving a Single Object

client = Client.find(10)

client = Client.take

client = Client.first

client = Client.last

Client.find_by first_name: ‘Lifo’

Client.where(first_name: ‘Lifo’).take

Client.find_by! first_name: ‘Lifo’

Retrieving Multiple Objects

client = Client.find([1, 10])

Client.take(2)

Client.first(2)

Client.last(2)

Retrieving Multiple Objects in Batches

User.all.each do |user|

 NewsLetter.weekly_deliver(user)

end

Conditions

Pure String Conditions

Client.where(“orders_count = ‘2’”)

Client.where(“orders_count = ?”, params[:orders])

Client.where(“orders_count = ?”, params[:orders])

Client.where(“orders_count = #{params[:orders]}”)

Client.where(orders_count: [1,3,5])

Post.where.not(author: author)

Ordering

Client.order(:created_at)

# OR

Client.order(“created_at”)

Selecting Specific Fields

Client.select(:name).distinct

Limit and Offset

Client.limit(5)

Client.limit(5).offset(30)

Group

Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).group(“date(created_at)”)

Having

Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).

 group(“date(created_at)”).having(“sum(price) > ?”, 100)

Overriding Conditions

Post.where(‘id > 10’).limit(20).order(‘id asc’).except(:order)

Post.where(‘id > 10’).limit(20).order(‘id desc’).only(:order, :where)

Client.where(“orders_count > 10”).order(:name).reverse_order

Null Relation

Post.none

Readonly Objects

client = Client.readonly.first

client.visits += 1

client.save

Optimistic Locking

c1 = Client.find(1)

c2 = Client.find(1)

c1.first_name = “Michael”

c1.save

c2.name = “should fail”

c2.save # Raises an ActiveRecord::StaleObjectError

Find or Build a New Object

find_or_create_by

Client.find_or_create_by(first_name: ‘Andy’)

find_or_initialize_by

The find_or_initialize_by method will work just like find_or_create_by but it will call new instead of create. This means that a new model instance will be created in memory but won’t be saved to the database. Continuing with the find_or_create_by example, we now want the client named ‘Nick’:

Finding by SQL

Client.find_by_sql(“SELECT * FROM clients

 INNER JOIN orders ON clients.id = orders.client_id

 ORDER BY clients.created_at desc”)

Existence of Objects

Client.exists?(1)

Calculations

Client.coun

Client.where(first_name: ‘Ryan’).count

Client.includes(“orders”).where(first_name: ‘Ryan’, orders: { status: ‘received’ }).count

Client.average(“orders_count”)

Client.minimum(“age”)

Client.maximum(“age”)

Client.sum(“orders_count”)

Form Helpers

<%= form_tag do %>

A Generic Search Form

<%= form_tag(“/search”, method: “get”) do %>

 <%= label_tag(:q, “Search for:”) %>

 <%= text_field_tag(:q) %>

 <%= submit_tag(“Search”) %>

<% end %>

Checkboxes

<%= check_box_tag(:pet_dog) %>

<%= label_tag(:pet_dog, “I own a dog”) %>

<%= check_box_tag(:pet_cat) %>

<%= label_tag(:pet_cat, “I own a cat”) %>

Radio Buttons

<%= radio_button_tag(:age, “child”) %>

<%= label_tag(:age_child, “I am younger than 21”) %>

<%= radio_button_tag(:age, “adult”) %>

<%= label_tag(:age_adult, “I’m over 21”) %>

Helpers

<%= text_area_tag(:message, “Hi, nice site”, size: “24×6”) %>

<%= password_field_tag(:password) %>

<%= hidden_field_tag(:parent_id, “5”) %>

<%= search_field(:user, :name) %>

<%= telephone_field(:user, :phone) %>

<%= date_field(:user, :born_on) %>

<%= datetime_field(:user, :meeting_time) %>

<%= datetime_local_field(:user, :graduation_day) %>

<%= month_field(:user, :birthday_month) %>

<%= week_field(:user, :birthday_week) %>

<%= url_field(:user, :homepage) %>

<%= email_field(:user, :address) %>

<%= color_field(:user, :favorite_color) %>

<%= time_field(:task, :started_at) %>

<%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %>

<%= range_field(:product, :discount, in: 1..100) %>

The Select and Option Tags

<%= select_tag(:city_id, ‘<option value=”1″>Lisbon</option>…’) %>

TIme zone

<%= time_zone_select(:person, :time_zone) %>

Country select

https://github.com/stefanpenner/country_select

Using Date and Time Form

<%= select_date Date.today, prefix: :start_date %>

<%= select_year(2009) %>

<%= select_year(Time.now) %>

Uploading Files

<%= f.file_field :picture %>

layout helpers

<%= javascript_include_tag “main”, “columns” %>

<%= stylesheet_link_tag “http://example.com/main.css” %>

<%= image_tag “header.png” %>

<%= video_tag “movie.ogg” %>

<%= audio_tag “music.mp3” %>

Easy way to deploy Rails 4 application in Unicorn with Nginx

In this post I will show you how to host our rails application with unicorn and nginx

The first step is obviously to install nginx for that go to your control terminal then type

sudo apt-get install “nginx”

After the installation go to /etc/nginx/sites_enabled/ – (or wherever you installed nginx)

in this sites_enabled folder you have default.conf file delete that file and create new file called nginx.conf

server
{
listen 80 default;
#server_name example.com;
root /home/ideology/test_server_nginx/public;
try_files $uri/index.html $uri @unicorn;
location @unicorn {
proxy_pass http://localhost:3000;
}

error_page 500 501 502 503 /404.html;
}

save the file with above code

Now In your rails application folder gemfile.rb add gem “unicorn” and run bundle install

Then start your rails application with unicorn with port 3000

    /application_folder/unicorn -p 3000

Then you can seen your application in browser with nginx server at port 80

Thats all! very simple yes?……

To change environment to production

RAILS_ENV=production rake db:migrate

and then in your boot.rb file add this lines

require ‘securerandom’
ENV[‘SECRET_KEY_BASE’] = SecureRandom.hex

then start your rails application unicorn server

RAILS_ENV=production unicorn -p 3000

And thats all your environment is changed to production now ,

But this is just a fast start up only this is not the correct solution to host your application you need additionally unicorn configuration files for further reference http://unicorn.bogomips.org/