Explain what is ORM (Object-Relationship-Model) in Rails?
Mention what is Rails Migration?
Explain what is rake in Rails?
Explain what is Ruby on Rails?
What is the purpose of the resources method in the code snippet below?
What is the use of load and require in Ruby?
List out what can Rails Migration do?
Mention what is the role of Rails Controller?
Explain how you define Instance Variable, Global Variable and Class Variable in Ruby?
How Is Visibility Of Methods Changed In Ruby (encapsulation)?
Mention what are the positive aspects of Rails?
What Is The Difference Between Nil And False In Ruby?
What Is MVC? And How It Works?
What Are Helpers And How To Use Helpers In ROR?
Mention what are the limits of Ruby on Rails?
How Many Types Of Associations Relationships Does A Model Have?
Explain what is a class library in Ruby?
Mention what is the difference in scope for these two variables: @@name and @name?
Explain what is the role of sub-directory app/controllers and app/helpers?
Mention what is the difference between a gem and a plugin in Ruby?
What Do You Mean By Render And Redirect_to?
What Are The Various Components Of Rail?
Explain what is Rails Active Record in Ruby on Rails?
How Many Types Of Relationships Does A Model Has?
Practical test: Genres of music
What is the difference between symbol and string?
What is the use of Destructive Method?
Explain Ruby on Rails Exception Handling
How should you use nested layouts?
How does Ruby on Rails use the Model View Controller (MVC) framework?
What is the purpose of the rakefile available in the demo directory in Ruby?
Explain what is Interpolation in Ruby?
What is the difference between &&, || operators and "and, or"?
Explain what is Polymorphic Association in Ruby on Rails?
Mention what is the purpose of RJs in Rails?
What Things We Can Define In The Model?
What Is The Difference Between Delete And Destroy?
Mention what is the function of garbage collection in Ruby on Rails?
Mention what is the difference between the Observers and Callbacks in Ruby on Rails?
What exactly are Harnesses and Fixtures in the Ruby?
Mention what is the difference between calling super() and super call?
What Do You Mean By Naming Convention In Rails?
Does Ruby Support Single Inheritance/multiple Inheritance Or Both?
Hw would you choose between Belongs_to And Has_one?
What Is The Difference Between "Save" And "Save!"?
What is the difference between content_for and yield?
What Are Filters? And How Many Types Of Filters Are There In Ruby?
How to rollback a specific migration?
How to check if a specific key is present in a hash or not?
Explain the difference between Page, Action, Fragment, Low-Level, SQL caching types.
What is the Difference Between Gem And Plugin?
What is ActiveJob? When should we use it?
How To Find Second Max Element From Database?
What is the difference between string and text in Rails?
How Many Types Of Callbacks Available In Ror?
What is the best thing which you find about the Ruby on Rail so far?
How Do I Find Only Duplicate Entries In A Database Table?
How To Use Two Databases Into A Single Application?
Node.js vs Ruby on Rails. Which would you choose?
ORM or Object Relationship Model in Rails indicate that your classes are mapped to the table in the database, and objects are directly mapped to the rows in the table.
Rails Migration enables Ruby to make changes to the database schema, making it possible to use a version control system to leave things synchronized with the actual code.
Rake is a Ruby Make; it is a Ruby utility that substitutes the Unix utility ‘make’, and uses a ‘Rakefile’ and ‘.rake files’ to build up a list of tasks. In Rails, Rake is used for normal administration tasks like migrating the database through scripts, loading a schema into the database, etc.
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.
- Ruby: It is an object-oriented programming language inspired by PERL and Python
- Rails: It is a framework used for building web applications
Defining routes with the resources
method automatically generates routes for the seven standard RESTful actions:
- GET /messages
- POST /messages
- GET /messages/new
- GET /messages/:id/edit
- GET /messages/:id
- PATCH/PUT /messages/:id
- DELETE /messages/:id
- You use
load()
to execute code - use
require()
to import libraries.
Rails Migration can do following things
- Create table
- Drop table
- Rename table
- Add column
- Rename column
- Change column
- Remove column and so on
The Rails controller is the logical center of the application. It facilitates the interaction between the users, views, and the model. It also performs other activities like
- It is capable of routing external requests to internal actions. It handles URL extremely well
- It regulates helper modules, which extend the capabilities of the view templates without bulking of their code
- It regulates sessions; that gives users the impression of an ongoing interaction with our applications
- Ruby Instance variable begins with — @
- Ruby Class variables begin with — @@
- Ruby Global variables begin with — $
By applying the access modifier:
- Public,
- Private and
- Protected
Rails provides many features like:
- Meta-programming: Rails uses code generation but for heavy lifting it relies on meta-programming. Ruby is considered as one of the best language for Meta-programming.
- Active Record: It saves object to the database through Active Record Framework. The Rails version of Active Record identifies the column in a schema and automatically binds them to your domain objects using metaprogramming
- Scaffolding: Rails have an ability to create scaffolding or temporary code automatically
- Convention over configuration: Unlike other development framework, Rails does not require much configuration, if you follow the naming convention carefully
- Three environments: Rails comes with three default environment testing, development, and production.
- Built-in-testing: It supports code called harness and fixtures that make test cases to write and execute.
False is a boolean datatype, Nil is not a data type it have object_id 4.
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.
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.
Ruby on Rails has been designed for creating a CRUD web application using MVC. Some of the features that Rails does not support include:
- Foreign key in databases
- Linking to multiple database at once
- Soap web services
- Connection to multiple database servers at once
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
- has_and_belongs_to_many
Ruby class libraries consist of a variety of domains, such as thread programming, data types, various domains, etc. These classes give flexible capabilities at a high level of abstraction, giving you the ability to create powerful Ruby scripts useful in a variety of problem domains. The following domains which have relevant class libraries are,
- GUI programming
- Network programming
- CGI Programming
- Text processing
The difference in scope for these two variables is that:
- @@name is a class variable
- @name is an instance variable
- App/controllers: A web request from the user is handled by the Controller. The controller sub-directory is where Rails looks to find controller classes
- App/helpers: The helper’s sub-directory holds any helper classes used to assist the view, model and controller classes.
- Gem: A gem is a just ruby code. It is installed on a machine, and it’s available for all ruby applications running on that machine.
- Plugin: Plugin is also ruby code, but it is installed in the application folder and only available for that specific application.
-
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.
- 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.
-
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.
Rails active record is the Object/Relational Mapping (ORM) layer supplied with Rails. It follows the standard ORM model as
- Table map to classes
- Rows map to objects
- Columns map to object attributes
- has_one
- belongs_to
- has_many
- has_many :through
What do you mean by the term Scaffolding and what sort of advantages the Ruby can offer when it comes to same?
While developing the projects, the users often have to write codes in the early stage of development. These codes help building the application in a very reliable manner and quickly and also, a close eye can be kept on the working of some major components with this approach. In Ruby, the scaffolding is done automatically and the users are free to concentrate on the core development only from the first day of development.
You will likely receive a variety of potential answers for an open-ended coding question like this, but here are two of the most straightforward approaches to creating a route. The most straightforward solution would be to create a simple route that specifies the controller action to call and passes the genre of music as a parameter. If the genre parameter is not included in the list of valid genres, the action will raise an ActionController::RoutingError
and redirect to a 404 page.
get 'music/:genre' => 'music#genre'
Alternatively, a better solution would be to use resource routing which comes with the added benefit of URL generation helpers. You can use the constraints option to verify the validity of a route by checking the parameter against a list of genres. This method requires that the parameter name for the genre be passed as :id
and would look something like this:
genres = %w|classical rock house country hip_hop rnb|
resource :music, only: [:show], constraints: {id: Regexp.new(genres.join('|'))}
- Symbols have two nice properties compared to strings which can save you memory and CPU time
The difference remains in the
object_id
, memory and process time for both of them when used together at one time - Strings are considered as mutable objects. Whereas, symbols, belongs to the category of immutable Strings objects are mutable so that it takes only the assignments to change the object information. Whereas, information of, immutable objects gets overwritten.
Distructive methods are used to change the object value permanently by itself using bang (!
) operator.
sort
returns a new array and leaves the original unchanged.sort!
returns the same array with the modification.
The !
indicates it’s a destructive method. It will overwrite the current array with the new result and returns it.
The general flow of begin/rescue/else/ensure/end looks like this:
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
rescue SomeOtherException => some_other_variable
# code that deals with some other exception
else
# code that runs only if *no* exception was raised
ensure
# ensure that this code always runs, no matter what
# does not change the final value of the block
end
You can leave out rescue
, ensure
or else
.
Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, like:
def foo
# ...
rescue
# ...
end
The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc.
A generated Rails application has a default layout and it’s defined in the app/views/layouts/application.html.erb. On the screen above there is only one dynamic block - it’s the body, the footer, the header and the sidebar are common blocks for each page. So the code for the layout may look like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<%= render 'shared/header' %>
<%= render 'shared/sidebar' %>
<%= yield %>
<%= render 'shared/footer' %>
</html>
The yield
in the code above is the place in which any action template will be rendered. This is a default Rails behavior.
Can you explain the difference between ActiveSupport’s “HashWithIndifferentAccess” and Ruby’s “Hash”?
The HashWithIndifferentAccess
class will treat symbol keys and string keys as equivalent while the Hash
class in Ruby will use the stricter = = comparison on keys—an equivalent string key will not retrieve the value for a given symbol key.
Web development can often be divided into three separate but closely integrated subsystems:
- Model (Active Record): The model handles all the data logic of the application. In Rails, this is handled by the Active Record library, which forms the bridge between the Ruby program code and the relational database.
- View (Action View): The view is the part of the application that the end user sees. In Rails, this is implemented by the Action View library, which is based on Embedded Ruby (ERB) and determines how data will be presented.
- Controller (Action Controller): The controller is like the data broker of an application, handling the logic that allows the model and view to communicate with one another. This is called the Action Controller in Rails.
The purpose of this simple question is to make sure a developer is familiar with a test-driven development. A beginner may not have dealt with this file yet. The rakefile is similar to the makefile in Unix, and assists with packaging and testing Rails code. It’s used by the rake utility, which ships natively with the Ruby installation.
Ruby Interpolation is the process of inserting a string into a literal. By placing a Hash (#) within {} open and close brackets, one can interpolate a string into the literal.
“&&” has higher precedence than “||” like in most other mainstream languages; but “or” and “and” in Ruby have the same precedence level.
Consider:
(func1 || func2 && func3) // interpreted as (func1 || (func2 && func3))
but
(func1 or func2 and func3) // interpreted as ((func1 or func2) and func3)
Polymorphic Association allows an ActiveRecord object to be connected with Multiple ActiveRecord objects. A perfect example of Polymorphic Association is a social site where users can comment on anywhere whether it is a videos, photos, link, status updates etc. It would be not feasible if you have to create an individual comment like photos_comments, videos_comment and so on.
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.
RJs is a template that produces JavaScript which is run in an eval block by the browser in response to an AJAX request. It is sometimes used to define the JavaScript, Prototype and helpers provided by Rails.
There are lot of things you can define in models, the 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
- The Delete method essentially deletes a row (or an array of rows) from the database.
- Destroy on the other hand allows for a few more options. First, it will check any callbacks such as before_delete, or any dependencies that we specify in our model. Next, it will keep the object that just got deleted in memory; this allows us to leave a message saying something like " 'Object_name' has been deleted." Lastly, and most importantly, it will also delete any child objects associated with that object.
-
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 a Proc (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.
The functions of garbage collection in Ruby on Rails includes
- It enables the removal of the pointer values which is left behind when the execution of the program ends
- It frees the programmer from tracking the object that is being created dynamically on runtime
- It gives the advantage of removing the inaccessible objects from the memory, and allows other processes to use the memory
-
Rails Observers: Observers is same as Callback, but it is used when method is not directly associated to object lifecycle. Also, the observer lives longer, and it can be detached or attached at any time. For example, displaying values from a model in the UI and updating model from user input.
-
Rails Callback: Callbacks are methods, which can be called at certain moments of an object’s life cycle for example it can be called when an object is validated, created, updated, deleted, A call back is short lived. For example, running a thread and giving a call-back that is called when thread terminates
These are basically the supporting codes with the help of which the users can easily write and can run the test cases. With the help of rake, the users can then simply proceed with the automated tests.
- super(): A call to super() invokes the parent method without any arguments, as presumably expected. As always, being explicit in your code is a good thing.
- super call: A call to super invokes the parent method with the same arguments that were passed to the child method. An error will therefore occur if the arguments passed to the child method don’t match what the parent is expecting.
With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been permitted. This means that you'll have to make a conscious decision about which attributes to permit for mass update. This is a better security practice to help prevent accidentally allowing users to update sensitive model attributes.
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.
Ruby Supports only Single Inheritance
The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well.
The has_one relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier.
-
Save! performs all validations and callbacks. If any validation returns false, save! throws an error and canceles the save.
-
Save does not throw any error in the case above, but canceles the save. Also, the validators can be bypassed.
yield
is how you specify where your content areas is going to go within a layout. You might have something like this:
<div>
<h1> This is the wrapper!</h1>
<%= yield :my_content %>
</div>
content_for
is how you specify which content is going to be rendered into which content area. You might have something like this:
<% content_for :my_content do %>
This is the content.
<% end %>
- 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).
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash.
flash
is a object of Actiondispatch
class.
rake db:rollback STEP=1
s a way to do this, if the migration you want to rollback is the last one applied. You can substitute 1 for however many migrations you want to go back.
rake db:migrate:down VERSION=20100905201547
will roll back the specific file.
Hash's key? method tells you whether a given key is present or not.
session.key?("user")
Yes. Rails gives you complete freedom to use all traditional means of scaling an application. Things like memcached
, caching full pages, caching fragments are all supported. You can use any standard CDN to serve your media and static content as well. Database scaling using sharding is supported. Finally Heroky makes your life easier by giving you the flexibility to scale up/down based on your need. Mostly websites have a peak time during which you need more servers and then there is a sleep time. Heroku makes that on-demand scaling process simpler. Companies such as HireFireApp.com makes the autoscale process easier.
Rails provides a set of caching features out of the box.
- Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or NGINX) without having to go through the entire Rails stack.
- Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served.
- Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
- Russian Doll Caching. You may want to nest cached fragments inside other cached fragments. This is called Russian doll caching.
- Low-Level Caching. Sometimes you need to cache a particular value or query result instead of caching view fragments. The most efficient way to implement low-level caching is using the Rails.cache.fetch method.
- SQL Caching. Query caching is a Rails feature that caches the result set returned by each query. If Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
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.
- Can only be used application wide.
Active Job is a framework for declaring jobs and making them run on a variety of queuing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really.
Model.order("yourField DESC").limit(1).offset(1)
The difference relies in how the symbol is converted into its respective column type in query language.
:string | VARCHAR | :limit => 1 to 255 (default = 255)
:text | TINYTEXT, TEXT, MEDIUMTEXT, or LONGTEXT2 | :limit => 1 to 4294967296 (default = 65536)
- before_validation
- before_validation_on_create
- validate_on_create
- after_validation
- after_validation_on_create
- before_save
- before_create
- after_create
- after_save
Rack is the underlying technology behind nearly all of the web frameworks in the Ruby world. "Rack" is actually a few different things:
- An architecture - Rack defines a very simple interface, and any code that conforms to this interface can be used in a Rack application. This makes it very easy to build small, focused, and reusable bits of code and then use Rack to compose these bits into a larger application.
- A Ruby gem - Rack is is distributed as a Ruby gem that provides the glue code needed to compose our code.
It widely support Metaprogramming and unlike other frameworks, all the codes can be written through this approach very easily and without taking the other programs which are complex into consideration. Also, the tasks which are heavy can be accomplished with this approach in no time which is one of the best things in the ruby.
What sort of problems you have faced with Ruby on Rails and how do you think the same can affect the projects?
Well, everything has a few cons associated with it. Thus there are a few which are common with this framework as well. The first thing is it sometimes faces performance issues due to its complex nature. As it doesn't depend on the native threads, the same are often simulated in the Virtual Machine rather than in the Operating system. Also, the requirements on the workstation where it is to be installed are complex in terms of hardware requirement.
A Rails Engine is like a mini-application. Think of it as a nested Rails app. By "mounting" the engine in your routes file you are providing access to the mini-application via the specified path.
Rails::Engine allows you to wrap a specific Rails application or subset of functionality and share it with other applications or within a larger packaged application. Every Rails::Application is just an engine, which allows for simple feature and application sharing.
The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages and pre-processors such as CoffeeScript, Sass and ERB. It allows assets in your application to be automatically combined with assets from other gems.
Consider:
User.group(:email).having(count(email) > 1)
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).
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"
- Node.js is great for applications that are real-time. And which handle a lot of concurrent requests. Under these scenarios, data constantly goes between the client and server. These Real-Time Applications (RTAs) include chat apps, applications for collaborating and video conferencing. Whenever you’re worried about performance and scalability, you should turn to Node.js first before you consider Ruby on Rails.
- Rails is a better solution where your applications are very CPU intensive. And where development needs to happen quickly. Because Node.js is a single-threaded environment, it cannot cope well with handling data such as images and graphics. A computation on a big dataset in Node.js can simply block all the other requests that are coming in. Hence, rendering the advantage of Node.js void. You can have a prototype in short thrift, with little work, when you use Rails.