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.
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!
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.
render will render a particular view using the instance variables available in the action.
For example if a render was used for the new action, when a user goes to /new, the new action in the controller is called, instance variables are created and then passed to the new view. Rails creates the html for that view and returns it back to the user's browser. This is what you would consider a normal page load.
redirect_to will send a redirect to the user’s browser telling it to re-request a new URL as 302 redirect response. Then the browser will send a new request to that URL and it will go through the action for that URL, oblivious to the fact that it was redirected to. None of the variables created in the action that caused the redirect will be available to the redirected view. This is what happens when you click on ‘Create’ in a form and the object is created and you’re redirected to the edit view for that object.
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”
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.
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
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.
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.
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
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
Regular adaptation to changing circumstances
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 symbol in Ruby on rails act the same way as the string but the difference is in their behaviors that are opposite to each other.
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 ofimmutable.
Strings objects are mutable so that it takes only the assignments to change the object information. Whereas, information of, immutable objects gets overwritten.
-String objects are written like
Symbols are used to show the values for the actions like equality or non-equality to test the symbols faster then the string values.
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.
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.
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
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.
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.
MVC (Model-View-Controller) is the architecture that provides flexibility and scalability of the applications.
It is almost having the same concept in any other language like PHP, Perl or Python. It is one of the major used architecture involved today due to its simplicity.
Controller is the main part in this kind of architecture where it handles the request that is coming from another controller.
Controller contacts the view and passes on the request to the view and it also interacts with the model to define the type of request.
Model is responsible for interacting with the database and provides the responses to the controller.
Controller takes the response and gives the response in the output form to the user that has made the request.
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.
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.
render example: render :action, render :partial etc. redirect example: redirect_to :controller => ‘users’, :action => ‘new’
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.
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;
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.
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.
The components involved in defining the model are as follows:
Validations: this is one of the very essential components and it defines the validations that are being put up on the input type of stream like validate_presence_of, format_of, etc.
Relationship: this is another type of component that describe the relationship between different types of components and it shows the relationship in the form of has_one, has_many, etc.
Callbacks: this is essential when it comes to respond after the failure and it allows the application to have certain functionality during failure. This can be given as before_save, after_save, etc.
Validation group settings: allow users to define the installed plugin settings.
Active record association relationship: allows current records to be actively having the relationship between one another.
for..in untill..end while..end do..end
Note: You can also use each to iterate a array as loop not exactly like loop
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.
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).
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
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.
There are lot of advantages of using ruby on rails.
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.
-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.
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.
By applying the access modifier : Public , Private and Protected access Modifier
A parameter represents a value that the method expects you to pass when you call it.
An argument represents the value you pass to a method parameter when you call the method. The calling code supplies the arguments when it calls the method.
In simple words, parameters appear in method definitions; arguments appear in method calls.
For example, in below method, variables param1 and param2 are the parameters
def foo_method(param1, param2): ....... end
while calling the method, arg1 and arg2 are the arguments
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.
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.
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.
If you want to set up a one-to-one relationship between two models, you'll need to add belongs_to to one, and has_one to the other. How do you know which is which?
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.
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.
A request.xhr tells the controller that the new Ajax request has come, It always return Boolean values (TRUE or FALSE)
Request from the request.xhr displays the controller that manages and creates the new AJAX that is being handled by the new controller.
The Boolean values that are retured should generate only TRUE or FALSE. These values are used to be inserted for this purpose.
The request.xhr is being shown in a program shown below as:
def create return unless request.xhr? @imageable = find_imageable @image = @imageable.images.build(params[:imageable]) @image.save render :layout => false end
False is a boolean datatype, Nil is not a data type it have object_id 4.
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.
Mysql: select * from users group by first,email having count(*) > 1