Skip to main content

ruby on rails Interview questions.....


1. What is Rails?

1. Rails is a extremely productive web-application framework written in Ruby language by David Hansson.

2. Rails are an open source Ruby framework for developing database-backend web applications.

3. Rails include everything needed to create a database-driven web application using the Model-View-Controller (MVC) pattern.

2. What are the various components of Rail?

1. Action Pack: Action Pack is a single gem that contains Action Controller, Action View and Action Dispatch. The “VC” part of “MVC”.

Action Controller: Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action.

Services provided by Action Controller include session management, template rendering, and redirect management.

Action View:  Action View manages the views of your Rails application. It can create both HTML and XML output by default.

Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support.

Action Dispatch: Action Dispatch handles routing of web requests and dispatches them as you want, either to your application or any other Rack application. Rack applications are a more advanced topic and are covered in a separate guide called Rails on Rack.

2. Action Mailer: Action Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.

3. Active Model: Active Model provides a defined interface between the Action Pack gem services and Object Relationship Mapping gems such as Active Record. Active Model allows Rails to utilize other ORM frameworks in place of Active Record if your application needs this.

4. Active Record: Active Record are like Object Relational Mapping (ORM), where classes are mapped to table, objects are mapped to columns and object attributes are mapped to data in the table.

5. Active Resource: Active Resource provides a framework for managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.

6. Active Support: Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in Rails, both by the core code and by your applications.

3. Explain about RESTful Architecture.

RESTful: REST stands for Representational State Transfer. REST is an architecture for designing both web applications and application programming interfaces (API’s), that’s uses HTTP.

RESTful interface means clean URLs, less code, CRUD interface. CRUD means Create-READ-UPDATE-DESTROY. In REST, they add 2 new verbs, i.e, PUT, DELETE.

4. Why Ruby on Rails?

There are lot of advantages of using ruby on rails.

1. DRY Principal( Don’t Repeat Yourself): It is a principle of software development aimed at reducing repetition of code. “Every piece of code must have a single, unambiguous representation within a system”

2. Convention over Configuration: Most web development framework for .NET or Java force you to write pages of configuration code. If you follow suggested naming conventions, Rails doesn’t need much configuration.

3.  Gems and Plugins: RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing ruby programs and library.

Plugins: A Rails plugin is either an extension or a modification of the core framework. It provides a way for developers to share bleeding-edge ideas without hurting the stable code base. We need to decide if our plugin will be potentially shared across different Rails applications.

4. Scaffolding: Scaffolding is a meta-programming method of building database-backend software application. It is a technique supported by MVC frameworks, in which programmer may write a specification, that describes how the application database may be used. There are two type of scaffolding:

-static: Static scaffolding takes 2 parameter i.e your controller name and model name.
-dynamic: In dynamic scaffolding you have to define controller and model one by one.

5. Rack Support: Rake is a software task management tool. It allows you to specify tasks and describe dependencies as well as to group tasks in a namespace.

6. Metaprogramming: Metaprogramming techniques use programs to write programs.

7. Bundler: Bundler is a new concept introduced in Rails 3, which helps you to manage your gems for application. After specifying gem file, you need to do a bundle install.

8. Rest Support.

9. Action Mailer

5. What do you mean by render and redirect_to?

render causes rails to generate a response whose content is provided by rendering one of your templates. Means, it will direct goes to view page.

redirect_to generates a response that, instead of delivering content to the browser, just tells it to request another url. Means it first checks actions in controller and then goes to view page.

6. What is ORM in Rails?

ORM tends for Object-Relationship-Model, where Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.

7. How many Types of Associations Relationships does a Model have?

When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations. Active Record supports three types of associations:

one-to-one: A one-to-one relationship exists when one item has exactly one of another item. For example, a person has exactly one birthday or a dog has exactly one owner.

one-to-many: A one-to-many relationship exists when a single object can be a member of many other objects. For instance, one subject can have many books.

many-to-many: A many-to-many relationship exists when the first object is related to one or more of a second object, and the second object is related to one or many of the first object.

You indicate these associations by adding declarations to your models: has_one, has_many, belongs_to, and has_and_belongs_to_many.

8. What are helpers and how to use helpers in ROR?

Helpers are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view.

9. What are Filters?

Filters are methods that run “before”, “after” or “around” a controller action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.

10. What is MVC? and how it Works?

MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like this:

Request first comes to the controller, controller finds and appropriate view and interacts with model, model interacts with your database and send the response to controller then controller based on the response give the output parameter to view.

11. What is Session and Cookies?

Session is used to store user information on the server side. Maximum size is 4 kb. Cookies are used to store information on the browser side or we can say client side.

12. What is request.xhr?

A request.xhr tells the controller that the new Ajax request has come, It always return Boolean values (TRUE or FALSE)

13. What things we can define in the model?

There are lot of things you can define in models few are:

1. Validations (like validates_presence_of, numeracility_of, format_of etc.)
2. Relationships (like has_one, has_many, HABTM etc.)
3. Callbacks (like before_save, after_save, before_create etc.)
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model
5. ROR Queries in Sql
6. Active record Associations Relationship

14.  How many types of callbacks available in ROR?

 (1) before_validation
 (2) before_validation_on_create
 (3) validate_on_create
 (4) after_validation
 (5) after_validation_on_create
 (6) before_save
 (7) before_create
 (8) after_create
 (9) after_save

15. How to serialize data with YAML?

YAML is a straight forward machine parsable data serialization format, designed for human readability and interaction with scripting language such as Perl and Python.

YAML is optimized for data serialization, formatted dumping, configuration files, log files, internet messaging and filtering.

16. How to use two databases into a single application?

magic multi-connections allows you to write your model once, and use them for the multiple rails databases at the same time.

sudo gem install magic_multi_connection. After installing this gem, just add this line at bottom of your environment.rb require “magic_multi_connection”

17. What are the various changes between the Rails Version 2 and 3?

1. Introduction of bundler (new way to manage your gem dependencies)
2. Gemfile and Gemfile.lock (where all your gem dependencies lies, instead of environment.rb)
3. HTML5 support

18. What is TDD and BDD?

TDD stands for Test-Driven-Development and BDD stands for Behavior-Driven-Development.

19. What are the servers supported by ruby on rails?

RoR was generally preferred over WEBrick server at the time of writing, but it can also be run by:
Lighttpd (pronounced ‘lighty’) is an open-source web server more optimized for speed-critical environments.
Abyss Web Server- is a compact web server available for windows, Mac osX and Linux operating system.
Apache and nginx

20. What do you mean by Naming Convention in Rails.

Variables: Variables are named where all letters are lowercase and words are separated by underscores. E.g: total, order_amount.

Class and Module: Classes and modules uses MixedCase and have no underscores, each word starts with a uppercase letter. Eg: InvoiceItem

Database Table: Table name have all lowercase letters and underscores between words, also all table names to be plural. Eg: invoice_items, orders etc

Model: The model is named using the class naming convention of unbroken MixedCase and always the singular of the table name.

For eg: table name is might be orders, the model name would be Order. Rails will then look for the class definition in a file called order.rb in /app/model directory. If the model class name has multiple capitalized words, the table name is assumed to have underscores between these words.

Controller: controller  class names are pluralized, such that OrdersController would be the controller class for the orders table. Rails will then look for the class definition in a file called orders_controlles.rb in the /app/controller directory.

21. What is the log that has to seen to check for an error in ruby rails?

Rails will report errors from Apache in log/apache.log and errors from the ruby code in log/development.log. If you having a problem, do have a look at what these log are saying.

22. How you run your Rails application without creating databases?

You can run your application by uncommenting the line in environment.rb
path=> rootpath conf/environment.rb
config.frameworks- = [action_web_service, :action_mailer, :active_record

23. How to use sql db or mysql db without defining it in the database.yml?

You can use ActiveRecord anywhere
require “rubygems”
require “active_record”
ActiveRecord::Base.establish_connection({
               :adapter=> ‘postgresql’, :user=>’foo’, :password=> ‘abc’, :database=>’whatever’})

24. GET and POST Method?

GET is basically for just getting (retrieving) data, whereas POST may involve anything, like storing or updating data, or ordering a product, or sending E-mail.

===============================
Hi Guys, Hope you all are fine, Well I think that I should Post something different in my blog, so that It will help you to get some more knowledge :) , So I came with Interview Questions, Hope this will help you a lot, I will update it regularly, If I found something Interesting. Well If you are experienced, I hope this should help you. All the Questions are dynamically Typed.

Q1. What is request.xhr?
Sol: A request.xhr tells the controller that the new Ajax request has come, It always return TRUE or FALSE

Q2. What is the Difference between Static and Dynamic Scaffolding?
Sol: The Syntax of Static Scaffold is like this:
ruby script/generate scaffold User Comment
Where Comment is the model and User is your controller, So all n all static scaffold takes 2 parameter i.e your controller name and model name, whereas in dynamic scaffolding you have to define controller and model one by one.

Q3. What is the Difference between Symbol and String?

Q4. What is Session and Cookies?
Sol: Session: are used to store user information on the server side.
cookies: are used to store information on the browser side or we can say client side
Session : say session[:user] = “puneet” it remains when the browser is not closed

Q5. Why Ruby on Rails?
Sol: There are lot of advantages of using ruby
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept

Q6. What is MVC? and how it Works?
Sol: MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like this: Request first comes to the controller, controller finds and appropriate view, your view interacts with model, model interacts with your database, for Example your url is something like this:

http://localhost:3000/users/new

here users is your controller and new is your method, there must be a file in your views/users folder named new.html.erb, so once the submit button is pressed, User model or whatever defined in the rhtml form_for syntax, will be called and values will be stored into the database.

Q7. What things we can define in the model?
Sol: There are lot of things you can define in models few are:
1. Validations (like validates_presence_of, numeracility_of, format_of etc.)
2. Relationships(like has_one, has_many, HABTM etc.)
3. Callbacks(like before_save, after_save, before_create etc.)
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model
5. ROR Queries in Sql

Q8. What is ORM in Rails?
Sol: ORM tends for Object-Relationship-Model, it means that your Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.

Q9. How many Types of Relationships does a Model has?
Sol: * (1) has_one
* (2) belongs_to
* (3) has_many
* (4) has_many :through

Q10. What is the difference between has_and_belongs_to_many and has_many :through ?

Q11.  What is the difference between rails version 2.2.2 with the older ones?

Q12. Difference between render and redirect?
Sol: render example: render :action, render :partial etc.
redirect example: redirect_to :controller => ‘users’, :action => ‘new’

Q13. How to use sql db or mysql db. without defining it in the database.yml
Sol. http://stuff.lilleaas.net/active_record_anywhere

Q14. What are helpers and how to use helpers in ROR?
Sol. Helpers (“view helpers”) are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It’s best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output.

Q15. What is Active Record?
Sol. Active Record are like Object Relational Mapping(ORM), where classes are mapped to table and objects are mapped to colums in the table

Q16. Ruby Supports Single Inheritence/Multiple Inheritence or Both?
Sol. Ruby Supports only Single Inheritnece

Q17. How many types of callbacks available in ROR?
Sol. * (-) save
* (-) valid
* (1) before_validation
* (2) before_validation_on_create
* (-) validate
* (-) validate_on_create
* (3) after_validation
* (4) after_validation_on_create
* (5) before_save
* (6) before_create
* (-) create
* (7) after_create
* (8) after_save

Q18. Suppose in one of my method I am updating the attributes of table, in my model I have defined after_create do X, and after_save do Y. Which method will be called?

Q19. How to use two database into a Single Application?
Sol. http://magicmodels.rubyforge.org/magic_multi_connections/, According to this link : ActiveRecord models are allowed one connection to a database at a time, per class. Ruby on Rails sets up the default connection based on your database.yml configuration to automatically select development, test or production.
But, what if you want to access two or more databases – have 2+ connections open – at the same time. ActiveRecord requires that you subclass ActiveRecord::Base.
That prevents you doing migrations from one database to another. It prevents you using one set of model classes on two or more databases with the same schema.
Magic Multi-Connections allows you to write your models once, and use them for multiple Rails databases at the same time. How? Using magical namespacing.

screenshot

To do this :
[A] sudo gem install magic_multi_connections
[B] require ‘magic_multi_connections’
Add the following to the bottom of your environment.rb file
You can also find examples on this link : http://magicmodels.rubyforge.org/magic_multi_connections/

“Updated Set of Questions for Rails 3”

Q20. Tell us the changes between the Rails version 2 and 3?
Sol. *  (1) Introduction of bundler (New way to manage your gem dependencies)
* (2) Gemfile and Gemfile.lock (Where all your gem dependencies lies, instead of environment.rb)
* (3) A new .rb file in config/ folder, named as application.rb (Which has everything that previously environment.rb had)
* (4) Change in SQL Structure: Model.where(:activated => true)
* (5) All the mailer script will now be in app/mailers folder, earlier we kept inside app/models.
* (6) Rails3-UJS support. for links and forms to work as AJAX, instead of writing complex lines of code, we write :remote => true
* (7) HTML 5 support.
* (8) Changes in the model based validation syntax: validates :name, :presence => true
* (9) Ability to install windows/ruby/jruby/development/production specific gems to Gemfile.
group :production do
gem 'will_paginate'
end

Q21. What is bundler?
Sol: Bundler is a new concept introduced in Rails3, which helps to you manage your gems for the application. After specifying gems in your Gemfile, you need to do a bundle install. If the gem is available in the system, bundle will use that else it will pick up from the rubygems.org.

Q22. What is the Newest approach for find(:all) in Rails 3?
Sol: Model.where(:activated => true)

Q23. What is Gemfile and Gemfile.lock?

Ruby Interview Questions :

Q1. What is the Notation used for denoting class variables in Ruby?

Q2. What is the use of Destructive Method?

Q3. What is the use of load and require in Ruby?

Q4. What is the use of Global Variable in Ruby?

Q5. How does nil and false differ?

Q6. How is visibility of methods change in Ruby?

Q7. What is a Class Instance Variable

Q8. What are the rules and conventions to be followed in Ruby for naming a method?

Q9. What is the use of Super?

Q10. How is class method defined in Ruby?

Q11. What are the Operators available in Ruby?

Q12. What are the looping structure available in Ruby?

Q13. What is the scope of local variable?

Q14. What are the OOP supported by Ruby?

Q15. If Ruby over PHP, Why?

Q16. Garbage collection in Ruby?

Q17. Environment Variables in Ruby?

Q18. What are Float, Dig and Max?

Q19. What is Ruby Code blocks?

Q20. What kind of conditions ruby support?

Q21. Difference between puts and print

Some More Questions are here:
Q1. What is Agile methodology? What are their Processes?

Q2. Is there any technology apart from agile which we can use?

Q3. What are the servers supported by ruby on rails application?

Q4. What is new in Rails 3.0?

Q5. What is Meta-programming? How you are using it inside your rails application?

Q6. What is has_many?
Ans. It is a way of defining relationships among models. Correct, and Do you guys really know has_many is also an example of Meta-programming? Wondering, How?

Q7. What is TDD and BDD?
Hint: Test-Driven-Development and Behavior-Driven-Development

Q8. What is rspec, cucumber and Watir? And what it has to do with TDD and BDD?
==========
1. Why Ruby on Rails?
Ans:
 1.CRUD (convention over configuration)
2. DRY Principal (Do not repeat Your self )
3. Gems and Plugins
4. Pure OOP Concept
5. Scaffolding
6.. Rest Support
7.Action Mailer
8. Rake support
9. open source
10.Rpsec Suppot for testing

2. What are Ruby Names
Ans: Classes, variables, methods, constants and modules

3.  Difference between Symbol and String?
Ans Strings are  Mutable , Symbols arre immutable
Note:Mutable objects can be changed after assignment while immutable objects can only be overwritten

4. Difference between Application Server and Web Server
Ans:apache, nginx, IIS are web servers
mongrel, webrick, phusion passenger are app servers

App server is something which works with particular programming language and parses and executes the code
since mongrel and webrick can only work with rails, so they are app servers

Web servers are servers which can take the request from the browser.
Web servers normally works on port 80 though we can change the port in configuration
since mongrel and webrick can take that request directly, so they can be thought of as web servers but web servers do have a lot of other functionality like request pipeline, load balancing etc.
App servers lack these functionalities.

About Mongrel server:
mongrel work as web as well as app server if you are talking about dev environment
but in production, mongrel alone can not work it will be too slow
so we need a web server in front of mongrel


5. What is request.xhr?
Ans: A request.xhr tells the controller that the new Ajax request has come, It always return Boolean values (TRUE or FALSE)

6. What is ORM in Rails?
Ans: ORM tends for Object-Relationship-Model, it means that your Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.

7. Ruby Support Single Inheritance/Multiple Inheritance ?
Ans: Ruby Supports only Single Inheritance.
You can achieve Multiple Inheritance through MIXIN concept means you achieve using module by including it with classes.

8. What is the log that has to seen to check for an error in ruby rails?
Ans: Rails will report errors from Apache in log/apache.log and errors from the Ruby code in log/development.log. If you’re having a problem, do have a look at what these logs are saying. On Unix and Mac OS X you may run tail -f log/development.log in a separate terminal to monitor your application’s execution.

9. What is the difference between nil and false in ruby?
Ans: False is a boolean datatype, Nil is not a data type it have object_id 4

10. How is visibility of methods changed in Ruby (Encapsulation)?
Ans: By applying the access modifier : Public , Private and Protected access Modifier

11.What is agile development? What are the strenghts?
Agile software development refers to a group of software development methodologies based on iterative development, where requirements and solutions evolve through collaboration between self-organizing cross-functional teams
Advantages:

    Customer satisfaction by rapid, continuous delivery of useful software
    Working software is delivered frequently (weeks rather than months)
    Projects are built around motivated individuals, who should be trusted
    Continuous attention to technical excellence and good design
    Simplicity
    Self-organizing teams
    Regular adaptation to changing circumstances


12 what is observers
Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn’t directly related to its purpose, observers allow you to add the same functionality outside of a model. For example, it could be argued that a User model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn’t directly related to your model, you may want to consider creating an observer instead.

13.What are filters? and how many types of filters are there in ruby?
Filters are methods that are run before, after or “around” a controller action.
Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.
Filter can take one of three forms: method reference (symbol), external class, or inline method (proc).

    after_filter
    append_after_filter
    append_around_filter
    append_before_filter
    around_filter
    before_filter
    filter_chain
    prepend_after_filter
    prepend_around_filter
    prepend_before_filter
    skip_after_filter
    skip_before_filter
    skip_filter

14.Difference between  Gem and Plugin
GEM
1. Gem is a packaged ruby application using the packaging system defined by RubyGems.
2. Rails itself is a Gem
3. We can install,upgrade and query the gem version.
4. Gem installed for Ruby interpreter can be used system-wide by that interpreter.
Plugin
1. Plugin is an extension of Rails Framework.
2. Can not be upgraded by using a command. To upgrade one have to uninstall and then install upgraded version.
3. Has to be hooked into rails application. (has to have init.rb)
4. Have an install.rb file.
5. Can only be used application wide.
15.Mixins in Ruby
When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.
 Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.
Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
Let us examine the following sample code to gain an understand of mixin:
module A
def a1
end
def a2
end
end
module B
def b1
end
def b2
end
endclass Sample
include A
include B
def s1
end
end samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1
Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus you can say the class Sample shows multiple inheritance or a mixin.

Comments

  1. The article provided by you is very nice and it is very helpful to know the more informationRuby on Rails Online Training Hyderabad

    ReplyDelete

Post a Comment

Popular posts from this blog

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).?

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).) In rails?


1)change the gemfile in mysql version
 gem 'mysql2'

2)Change to mysql2 version
 gem 'mysql2','0.3.20'

Active Scaffold : Add radio buttons to your form ruby on rails ?

Active Scaffold : Add radio buttons to your form ruby on rails ?

The way to add radio buttons to your active scaffold create/update from is as shown below

#Controller

class UsersController < ApplicationController
active_scaffold :user do |config|
config.label = “Users”
config.columns = [:name, :gender]
config.columns[:gender].form_ui = :radio
config.columns[:gender].options[:options] = [['Male', '1'], ['Female','2']]
end
end

Get user accessing ip address in rails?

Get user accessing ip address rails?

request.ip ->returns the ip, whether is is a local proxy ip (localhost address) or not.
*request.remote_ip -> is smarter and gets the ip address of the client outside of local proxies.
3)If you are using apache in front of a mongrel, then remote_ip will return the source address of the request, which in this case will be local host because the Apache web server is making the request, so instead put this in your controller:

@remote_ip = request.env["HTTP_X_FORWARDED_FOR"]