Ruby On Rails Interview Questions

Q.What Is Rails? Ans: Rails is a extremely productive web-application framework written in Ruby language by David Hansson. Rails are an open source Ruby framework for developing database-backend web applications. Rails include everything needed to create a database-driven web application using the Model-View-Controller (MVC) pattern. Q.What Are The Various Components Of Rail? Ans: 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. 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. 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. 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. 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. 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. Q.Explain About Restful Architecture? Ans: 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. Q.Why Ruby On Rails? Ans: There are lot of advantages of using ruby on rails. 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” 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. 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. 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. 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. Metaprogramming: Metaprogramming techniques use programs to write programs. 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. Rest Support. Action Mailer Q.What Do You Mean By Render And Redirect_to? Ans: 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. Q.What Is Orm In Rails? Ans: 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. Q.How Many Types Of Associations Relationships Does A Model Have? Ans: 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. Q.What Are Helpers And How To Use Helpers In Ror? Ans: 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. Q.What Are Filters? Ans: 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. Q.What Is Mvc? And How It Works? Ans: 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. Q.What Is Session And Cookies? Ans: 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. Q.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) Q.What Things We Can Define In The Model? Ans: There are lot of things you can define in models few are: Validations (like validates_presence_of, numeracility_of, format_of etc.) Relationships (like has_one, has_many, HABTM etc.) Callbacks (like before_save, after_save, before_create etc.) Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model ROR Queries in Sql Active record Associations Relationship Q.How Many Types Of Callbacks Available In Ror? Ans: before_validation before_validation_on_create validate_on_create after_validation after_validation_on_create before_save before_create after_create after_save Q.How To Serialize Data With Yaml? Ans: 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. Q.How To Use Two Databases Into A Single Application? Ans: 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” Q.What Are The Various Changes Between The Rails Version 2 And 3? Ans: Introduction of bundler (new way to manage your gem dependencies) Gemfile and Gemfile.lock (where all your gem dependencies lies, instead of environment.rb) HTML5 support Q.What Is Tdd And Bdd? Ans: TDD stands for Test-Driven-Development and BDD stands for Behavior-Driven-Development. Q.What Are The Servers Supported By Ruby On Rails? Ans: 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 Q.What Do You Mean By Naming Convention In Rails. Ans: 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 Orders Controller 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. Q.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 having a problem, do have a look at what these log are saying. Q.How You Run Your Rails Application Without Creating Databases? Ans: You can run your application by uncommenting the line in environment.rb path=> rootpath conf/environment.rb config.frameworks-=) @image.save render :layout => false end Q.What Are The Different Components Of Rails ? Ans: The components used in Rails are as follows: Action Controller: it is the component that manages all other controllers and process the incoming request to the Rails application. It extracts the parameters and dispatches the response when an action is performed on the application. It provides services like session management, template rendering and redirect management. Action View: it manages the views of the Rails application and it creates the output in both HTML and XML format. It also provides the management of the templates and gives the AJAX support that is being used with the application. Active Record: It provides the base platform for the models and gets used in the Rails application. It provides the database independence, CRUID functionality, search capability and setting the relationship between different models. Action Mailer: It is a framework that provides email services to build the platform on which flexible templates can be implemented. Q.What Is The Purpose Of Load, Auto_load, And Require_relative In Ruby ? Ans: Load allows the process or a method to be loaded in the memory and it actually processes the execution of the program used in a separate file. It includes the classes, modules, methods and other files that executes in the current scope that is being defined. It performs the inclusion operation and reprocesses the whole code every time the load is being called. require is same as load but it loads code only once on first time. Auto_load: this initiates the method that is in hat file and allows the interpreter to call the method. require_relative: allows the loading to take place of the local folders and files. Q.What Is A Proc ? Ans: Everyone usually confuses procs with blocks, but the strongest rubyist can grok the true meaning of the question. Essentially, Procs are anonymous methods (or nameless functions) containing code. They can be placed inside a variable and passed around like any other object or scalar value. They are created by Proc.new, lambda, and blocks (invoked by the yield keyword). Blocks are very handy and syntactically simple, however we may want to have many different blocks at our disposal and use them multiple times. As such, passing the same block again and again would require us to repeat ourself. However, as Ruby is fully object-oriented, this can be handled quite cleanly by saving reusable code as an object itself. This reusable code is called aProc (short for procedure). The only difference between blocks and Procs is that a block is a Proc that cannot be saved, and as such, is a one time use solution. Q.What Is Unit Testing (in Classical Terms)? What Is The Primary Technique When Writing A Test ? Ans: Unit testing, simply put, is testing methods -- the smallest unit in object-oriented programming. Strong candidates will argue that it allows a developer to flesh out their API before it's consumed by other systems in the application. The primary way to achieve this is to assert that the actual result of the method matches an expected result. Q.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. Q.What Are The Looping Structures Available In Ruby ? Ans: for..in untill..end while..end do..end Note: You can also use each to iterate a array as loop not exactly like loop Q.How Is Visibility Of Methods Changed In Ruby (encapsulation) ? Ans: By applying the access modifier : Public , Private and Protected access Modifier Q.Dynamic Finders ? Ans: For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called first_name on your Client model for example, you getfind_by_first_name and find_all_by_first_name for free from Active Record. If you have a locked field on the Client model, you also get find_by_locked and find_all_by_lockedmethods. You can also use find_last_by_* methods which will find the last record matching your argument. You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an ActiveRecord::RecordNotFound error if they do not return any records, like Client.find_by_name!("Ryan") If you want to find both by name and locked, you can chain these finders together by simply typing "and" between the fields. For example, Client.find_by_first_name_and_locked("Ryan", true). Q.Finding By Sql ? Ans: If you'd like to use your own SQL to find records in a table you can use find_by_sql. The find_by_sql method will return an array of objects even if the underlying query returns just a single record. For example you could run this query: Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc") find_by_sql provides you with a simple way of making custom calls to the database and retrieving instantiated objects. Q.Pluck ? Ans: pluck can be used to query a single column from the underlying table of a model. It accepts a column name as argument and returns an array of values of the specified column with the corresponding data type. Client.where(:active => true).pluck(:id) # SELECT id FROM clients WHERE active = 1 Client.uniq.pluck(:role) # SELECT DISTINCT role FROM clients Q.Difference Between Rails 2 And Rails 3 ? Ans: I found 7 major Difference between rails 2 and rails 3 has: New Router Api, New mailer, New Active Record Query interface, Assets pipeline, Security Improvements, Unobtrusive JavaScript (UJS) , Dependency management with bundler. Q.What Is A Ruby Singleton Method ? Ans: A method which belongs to a single object rather than to an entire class and other objects. Before explaining about singleton methods I would like to give a small introduction about class methods. Class method: When you write your own class methods you do so by prefacing the method name with the name of the class. There are three ways to write a class method. The first way is to preface the class name with the method name(ClassMethods.method1). The second way is to preface the self keyword with the method name(self.method2). The third way is writing a sepetare class inside the class which contains the methods (class << self). Q.What Is Agile Development? What Are The Strengths? Ans: 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 Q.Difference Between Gem And Plugin? Ans: GEM Gem is a packaged ruby application using the packaging system defined by RubyGems.Rails itself is a Gem We can install,upgrade and query the gem version.Gem installed for Ruby interpreter can be used system-wide by that interpreter. Plugin Plugin is an extension of Rails Framework. Can not be upgraded by using a command. To upgrade one have to uninstall and then install upgraded version. Has to be hooked into rails application. (has to have init.rb) Have an install.rb file. 5. Can only be used application wide. Q.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 configurationsince 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. Q.What Is The Use Of Load And Require In Ruby? Ans: A method that loads and processes the Ruby code from a separate file, including whatever classes, modules, methods, and constants are in that file into the current scope. load is similar, but rather than performing the inclusion operation once, it reprocesses the code every time load is called. Q.Resource Routing & Difference Between Member Routes And Collection Routes ? Ans: Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code.Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as GET, POST, PUT and DELETE. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller. Q.How To Find Second Max Element From Database ? Ans: Rails Query:Model.order("yourField DESC").limit(1).offset(1) Mysql: SELECT * FROM yourTable ORDER BY yourField DESC LIMIT 1,1; Other sql ways: -select max(column_name) from table_name where column_name<(select max(column_name) from table_name) -SELECT Name FROM Employees group BY Salary DESCENDING limit 2; Q.What Is Rack ? Ans: Rack: a Ruby Webserver Interface Rack middleware is a way to filter a request and response coming into your application. Q.How Do I Find Only Duplicate Entries In A Database Table? Ans: Rails: User.group(:email).having("count(email)>1 Mysql: select * from users group by first,email having count(*) > 1 Contact for more on Ruby On Rails Online Training