Monday 18 February 2013

Nested Routes in Rails3


In this article I am going explain nested resouces in rails . I hope you all familiar with REST in rails I am not going to discuss REST nature here.Here just consider we two resouces named as Projects and Tasks , here I am assuming that every task is related to certain Project and without project there is no task. So I will do make association has_many between Projects and Tasks .it will look like following

 class Project < ActiveRecord::Base  
  attr_accessible :name  
  has_many :tasks ,:dependent => :destroy  
 end  
 class Task < ActiveRecord::Base  
  attr_accessible :name  
  belongs_to :project  
 end  

generally our routes.rb file is like the following

 routes.rb  
 -----------------  
 resources :projects  
 resources:tasks  

so lets we modify the routes as following

  resources  :projects do   
    resources :tasks  
  end  

that’s it REST will do the magic for us . so now we need to concern about how to create task by following REST full routes new_task_path wont work here , it will rise an error , so we must take care while using routes here, do not worry I will tell how to do this creating new task with using the following line

 <%= link_to 'New Task', new_project_task_path(@project) %>  

it will open form for creating new task , it will look like this and I have done small changes that to create new task I have modified target file , please observe it

 <%= form_for([@project,@task]) do |f| %>  
  <div class="field">  
   <%= f.label :project_id %><br />  
   <%= f.text_field :project_id %>  
  </div>  
  <div class="field">  
   <%= f.label :name %><br />  
   <%= f.text_field :name %>  
  </div>  
  <div class="actions">  
   <%= f.submit %>  
  </div>  
 <% end %>  

and the tasks controller new action and create action are look like the following

 def new  
   @project = Project.find(params[:project_id])  
   @task = Task.new  
 end  
 <br/>  
 def create  
   @project = Project.find(params[:project_id])  
   @task = Task.new(params[:task])  
   respond_to do |format|  
    if @task.save  
     format.html { redirect_to project_path(@project), notice: 'task was successfully created.' }  
    end  
   end  
  end  

and we can write delete link as follows

 <%= link_to "Delete task", project_task_path(@project, @task), :confirm => "Are you sure you want to delete this task?", :method => :delete %>  
 and also you can edit task by using following path   
 <%= link_to 'Edit task', edit_project_task_path(@project,@task) %>  

I hope this will help you to give some idea nested routes with rails .I welcome your comments on this article so that i can improve further .thank you

Thanks Ratnakar V
About the Author
Ratnakar is a Software Engineer, Blogger from India.His articles mainly focus on Ruby on Rails Technology.
Reach Him : Google+ Facebook Twitter
Read More

Saturday 9 February 2013

Mongodb Installation in ubuntu

Mongodb Installation.

.

Hi , in my previous article I posted how to work with mongoid with rails and some basics about mongodb Mongoid with RailsMongodb with Rails and here is installation steps of mongodb in ubuntu





Step 1 :
open terminal by typing shift+alt+T
Step 2 :
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
Step 3 :

Create a file in the following directory ,at your terminal type the following

cd /etc/apt/sources.list.d then
touch 10gen.list

open the file by typing following command

sudo nano  10gen.list
then enter the following line 
deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen
 press enter and then ctrl+X  it will ask to save file then press Y
Step 4 :

Then we need to reload the repository by using the following command at your terminal

sudo apt-get update

Now its the time to install 10 gen packages (mongodb maintained by 10gen)

Step 4 :
sudo apt-get install mongodb-10gen
This will install all 10gen packages required for mongodb , when this is done at terminal you see the following line
Adding user `mongodb' to group `mongodb' ... 
Adding user mongodb to group mongodb 
Done.

Thats it you have successfully installed mongodb in your system . Then try start/ stop mongodb services by using the following commands

sudo service mongodb start
sudo service mongodb stop
Connect to mongodb by using the following command at terminal
mongo
it will connect to default database 'test' , you can see in terminal following lines
MongoDB shell version: 2.2.2 
connecting to: test 
Welcome to the MongoDB shell. 
For interactive help, type "help". 
For more comprehensive documentation, see 
 http://docs.mongodb.org/ 
Questions? Try the support group 
 http://groups.google.com/group/mongodb-user 
You can use mongodb GUI tools , the following link will guide you through several tools choose any one of them
http://www.mongodb.org/display/DOCS/Admin+UIs 

I hope this will give some sort of idea how to install mongodb ..I welcome your comments on this article thank you

Cheers,
Ratnakar
About the Author
Ratnakar is a Software Engineer, Blogger from India.His articles mainly focus on Ruby on Rails Technology.
Reach Him : Google+ Facebook Twitter
Read More

Friday 1 February 2013

Mongoid with Rails 3


Hi, Every one , I feel that my posts are useful for you to get knowledge on Rails and please suggest me if you have any useful topics so that we will discuss more on those topics . here I am going to explain how Mongoid works with rails3 , here I explained some basics to get start with mongoid .
    as i have posted previously mongodb is so flexible and its document oreiented . We have sevaral ORM 's in the market we all know that ActiveRecord is one of the famous ORM for rails when we are dealing with relational databases . Now here we are dealing with ODM 's means Object Document Mapper . There are several ODM ' s are there few things i listed out here in conjuction with rails

  1.MongoMapper  
  2.Mongoid  
  3.Mongomatic  
  4.MongoODM  
  5.MongoModel  
  6.DriverAPILayer  

these are all ruby based ODM's Here i am going to create small application which will give some idea about how to use Mongoid

Step 1:

  install the mongoid gem by typing the following at your terminal  
   "gem install mongoid " or else you can add it your gem file  

Step2 : create a new rails application

 rails new mongoid_app  

Step3 : go to your mongoid_app

 cd monoid_app  

Step 4 : here I want to create two models Movie and Dancer and later i will associate both .
    First generate scaffold for movie model

 rails g scaffold Movie name:string   

which will create model , controller and veiws for movie model , in the same way create dancer model also
 rails g Dancer name:string  

then open your model and simply just include the following line in your model
 include Mongoid::Document  

follow the example below Ex :
 class Movie  
  include Mongoid::Document  
  field :name , type:String  
 end  

this will give ability to our class to act as a mongo document . Here we can see that our movie model contains only one field called name , if we want to add extra fields then no need of migrations here ,(oh sounds cool) simply add field name and type , once you enter the data and run the application it will add to database really how simple it is ! I will add one more field here

 class Movie  
  include Mongoid::Document  
  field :name , type:String  
  field :budget , type : Integer  
 end  

in the same way include Mongoid::Document to the Dancer model also .
 class Dancer  
  include Mongoid::Document  
  field :name , type:String  
 end  

now i will associate both models with has_many relation , just like the activerrecord relations we can add here also here I am going to establish Movie has_many dacers . See the following code snippet

 class Movie  
  include Mongoid::Document  
  field :name , type:String  
  field :budget , type : Integer  
 embeds_many :dancers  
 end  
and Dancer model is
 class Dancer  
  include Mongoid::Document  
  field :name , type:String  
  embedded_in :artist  
 end  
now we can query model simply by the following
 fetch Movie Model :  
  @movie = Movie.first  
 fetch movie related dancers  
  @dancers = @movie.dancers  

I hope this will help you to give some idea mongoid with rails .I welcome your comments on this article so that i can improve further .thank you Thanks Ratnakar V
About the Author
Ratnakar is a Software Engineer, Blogger from India.His articles mainly focus on Ruby on Rails Technology.
Reach Him : Google+ Facebook Twitter
Read More

Thursday 31 January 2013

Mongodb with rails

Mongodb Rails 3.

.
Hi , in this article i am going to explain few basic concepts of Mongodb , and this article entirely for beginers only .

Mongodb:

--> Mongodb is an open source document -oriented database system.

--> Its the type of NoSQL .document oriented means it storing data as JSON format , so all we have here json format , simply key ,value pairs , generally we can see in relational database all the data is stored in tables and we mantains relationships among the tables we called these as relational databases.

--> One of the greater advantage of document oriented databases is it does not store the unused data . Here is small example so that we can understand more deeply

 {  
   Name: “Ratnakar”,  
   Hobby: “Playing Guitar”  
 }  

this is we call document . As I said before document contains key , value where each key represents one column in relational database. And i have another record(document) which stores some more extra fields

 {  
   Name: “Ratnakar”,  
   Hobby: “Playing Guitar”  
 }  
  {  
   Name: “Ratnakar”,  
   Hobby: “Playing Guitar”  
   Designation : Developement Engineer,  
   Location : AP  
 }  

so if we observe clearly the difference between relational and document oriented databases , unlike the relational databases where each record would have the same set of fields and unused fields might be kept empty,there are no empty fields in documents

--> No need of joins becoz documents and arrays reduces need of joins and many of advantages are there .


         Document oriented                      Relational based  
 -----------------------------------              -----------------------------------  
 collections                                    databases  
 documents                                      tables  
 filelds (key ,value)                           row and column  

I hope this will give some sort of idea to start learning mongodb ..I welcome your comments on this article so that i can improve further .thank you

Cheers,
Ratnakar
About the Author
Ratnakar is a Software Engineer, Blogger from India.His articles mainly focus on Ruby on Rails Technology.
Reach Him : Google+ Facebook Twitter
Read More

Tuesday 29 January 2013

full calendar in rails3 , jquery full calendar in rails3

Hi , in this article i am going to explain how to work with

jquery full calendar along with rails 3

.

Step 1 : Install the gem by typing the following command at terminal or you can add it your gem file
    gem 'fullcalendar-rails'
     bundle install
you can find full documentation of jquery full calendar from the following link arshaw full calendar

Step 2: then add the following line in your application.js file
     //= require fullcalendar

Step 3: add the following line in your application.css file
    *= require fullcalendar

Step 4: then create calendar.js.coffee file add it your assets/javascript folder assets/javascripts/calendar.js.coffee

 $(document).ready ->  
  $('#calendar').fullCalendar  
   editable: true,  
   header:  
    left: 'prev,next today',  
    center: 'title',  
    right: 'month,agendaWeek,agendaDay'  
   defaultView: 'month',  
   height: 500,  
   slotMinutes: 30,  
   eventSources: [{  
    url: '/events',  
   }],  
   timeFormat: 'h:mm t{ - h:mm t} ',  
   dragOpacity: "0.5"  
   eventDrop: (event, dayDelta, minuteDelta, allDay, revertFunc) ->  
    updateEvent(event);  
   eventResize: (event, dayDelta, minuteDelta, revertFunc) ->  
    updateEvent(event);  
  <br/>  
 updateEvent = (the_event) ->  
  $.update "/events/" + the_event.id,  
   event:  
    title: the_event.title,  
    starts_at: "" + the_event.start,  
    ends_at: "" + the_event.end,  
    description: the_event.description  

Step 5: Create Event model by having the follwoing feilds title, description,start,end, allDay

Step 6: Now we need to create views and controller for Event Model , I hope you know how to create views and controller for Event model , i dont explaing those things here . Once you done with creating views and controller . Fullcalendar display event those are in json format , so we need to return json object i mean to say that we need to return events object in the form of json , so i am writing some simple code here look at this one .
In EventsController write the following snippet in index method

 class EventsController < ApplicationController  
  def index  
   @events = Event.scoped  
   @events = Event.between(params['start'], params['end']) if (params['start'] && params['end'])  
   respond_to do |format|  
    format.html # index.html.erb  
    format.json { render :json => @events }  
   end  
  end  
 end  


in the above snippet i have used scope (between) on Event model so we need to define scope on Event model , write the following code in Event Model.
 class Event < ActiveRecord::Base  
  scope :between, lambda {|start_time, end_time|  
   {:conditions => ["? < starts_at < ?", Event.format_date(start_time),      Event.format_date(end_time)] }  
  }  
  def self.format_date(date_time)  
   Time.at(date_time.to_i).to_formatted_s(:db)  
  end 
end 

we can tell to event model which fields we want to return back to calendar by specifying in json method , i am going to write as_json method in Event model
 class Event < ActiveRecord::Base  
  def as_json(options = {})  
   {  
    :id => self.id,  
    :title => self.title,  
    :description => self.description || "",  
    :start => starts_at.rfc822,  
    :end => ends_at.rfc822,  
    :allDay => self.all_day,  
    :recurring => false,  
    :url => Rails.application.routes.url_helpers.event_path(id),  
   }  
  end  
 end  

here i wrapped up json object with some fields , above i mentioned url attribute which holds path of respective event . When you click on calendar dates this will be invoked.

Step 7: Now dont forget to create event the following is the sample code for creating events .

 views/events/_form.html.erb  
 <%= form_for(@event) do |f| %>  
  <div class="field">  
   <%= f.label :title %><br />  
   <%= f.text_field :title %>  
  </div>  
  <div class="field">  
   <%= f.label :starts_at %><br />  
   <%= f.datetime_select :starts_at %>  
  </div>  
  <div class="field">  
   <%= f.label :ends_at %><br />  
   <%= f.datetime_select :ends_at %>  
  </div>  
  <div class="field">  
   <%= f.label :all_day %><br />  
   <%= f.check_box :all_day %>  
  </div>  
  <div class="field">  
   <%= f.label :description %><br />  
   <%= f.text_area :description %>  
  </div>  
  <div class="actions">  
   <%= f.submit %>  
  </div>  
 <% end %>  

Step 8: thats it you can view your events in calendar by adding following line in events/index.html.erb

 <div id = 'calendar'> </div>  
which will render full calendar view .

Step 9: thats it now set your roots and you can open your browser and type localhost:3000/events .
I hope this will help you to give some idea how to shedule events using fullcalendar in rails 3 .I welcome your comments on this article so that i can improve further .thank you

Cheers,
Ratnakar
About the Author
Ratnakar is a Software Engineer, Blogger from India.His articles mainly focus on Ruby on Rails Technology.
Reach Him : Google+ Facebook Twitter
Read More