Singular Resources
You may have encountered this without realizing it at some time. Until now, we've been discussing resources (such as "posts" and "users") that have a large number of them. It appears to be quite simple. These are represented simply with a single line in your config/routes.rb file, such as resources:users.
There are instances when there is just one resource that makes sense. A Person dashboard, for example, presents relevant data based on the user who is currently signed in. There is just one dashboard template, which is smart enough to present information relevant to the person who is now signed in.
Because there is just one dashboard in this scenario, displaying an "index" of dashboards makes little sense (it just changes based on who is logged in). We can also remark that because there is just one resource, we no longer need the id argument for any other actions that would typically require an ID to identify which resource we're acting on (like #show).
For a singular resource. the root file line would look like this:
# in config/routes.rb
resource :dashboard

You can also try this code with Online Javascript Compiler
Run Code
Remember that "resource" is singular, as is the phrase "dashboard." Many individuals make the mistake of writing "resource" instead of "resources" when they truly want plural resources (which are more common).
Because we no longer utilize #index, the $ rake routes for a single resource would only comprise 6 routes, and you would no longer see any of the:id sections of the routes, For example,
edit_dashboard GET /dashboard/edit(.:format) dashboards#edit

You can also try this code with Online Javascript Compiler
Run Code
Nested Routes
Sometimes nesting one resource inside another makes sense. For example, a list of lessons like this would fit under a list of courses. Thus you'd anticipate a URL along the lines of http://example.com/courses/1/lessons/3. This nesting is accomplished in the routes file by physically nesting one resource inside a block supplied to another, as shown below:
# config/routes.rb
TestApp::Application.routes.draw do
resources:courses do
resources :lessons
end
End

You can also try this code with Online Javascript Compiler
Run Code
When you go to the URL, you must provide the:id parameter for BOTH items. The $ rake routes for the preceding might look like this:
course_lesson GET /courses/:course_id/lessons/:id(.:format) lessons#show

You can also try this code with Online Javascript Compiler
Run Code
We can also make sure that you are being directed to the controller of the deepest nested resource, which is also the:id parameter, which will be referred to as simply:id (any parent resource parameters, as mentioned above, will be referred to precisely as course id).
View helpers are also built automatically in a sensible manner (as seen by the $ rake routes output). When using view helpers like #course lesson path, you must supply both parameters correctly, e.g. course lesson path (1,3).
Member and Collection Routes
You may wish to add another non-RESTful route to a resource at times. Use the #member method to add a route to a specific member of that resource:
# config/routes.rb
TestApp::Application.routes.draw do
resources :courses do
member do
get "preview"
# Preview a single course
end end end

You can also try this code with Online Javascript Compiler
Run Code
That path would correspond to the course #preview action.
If you want to create a non-RESTful route to your resource's whole collection (without having to supply the:id property, as with the index action), use the #collection method:
TestApp::Application.routes.draw do
resources :courses do
member do
get "preview"
# Preview a single course (requires ID) end collection do
get "upcoming" # Show a list of *all* upcoming courses (no ID needed)
end
end
End

You can also try this code with Online Javascript Compiler
Run Code
The upcoming route corresponds to the course's #upcoming action but does not accept an:id input.
If any of this sounds perplexing, experiment with them and run $ rake routes to see what is happening behind the scenes.
Redirects and Wildcard Routes
You could wish to give a URL for your user's convenience but link it straight to another one you're currently using. Make use of a redirect:
TestApp::Application.routes.draw do get 'courses/:course_name' => redirect('/courses/%{course_name}/lessons'), :as => "course" end

You can also try this code with Online Javascript Compiler
Run Code
That became intriguing quickly. The main objective here is to utilize the #redirect technique to send one route to another. It's a really simple way if your path is pretty simple. However, if you also want to communicate the original arguments, you must perform some acrobatics by capturing the parameter inside%here.
In the above example, we've also renamed the route for ease of use by utilizing an alias with the:as argument. This enables us to utilize that name in methods such as the #_path helpers. Again, use questions to test your $ rake routes.
Advanced Layouts: Nesting Layouts and Passing Information
View layouts were covered quite thoroughly in the Views course. However, one important issue includes generating numerous layouts for one page, which allows you to create distinct parts while still reusing many of the stylings you may want to maintain throughout your site (e.g. the footer). For example, your user pages may be styled differently from your home page. The initial impulse would be to create a separate stylesheet for each layout, but remember that Rails' Asset Pipeline merges all of your stylesheets regardless.
A better way to accomplish things is to instruct your layout to do something (whatever your layout would usually do) and then display another layout using the render:template => "your layout.html.erb" function. You're utilizing your layouts in the same way a view could use a partial view.
You can also use the #content for a method to transmit information from the initial layout to the one that is rendered. This allows you to implement logic in your main layout based on your separate layout files pass... The options are limitless.
For example, you may have a layout file called app/views/layouts/static pages.html.erb for your static pages. If this file exists, it will be displayed by default for views created by your StaticPagesController (a Rails default). But suppose you want your static pages to look nearly identical to the rest of the website, but you don't want the navbar to show across the top.
In this example, you would instruct your static pages.html.erb layout to call the application.html.erb layout while also passing it some specific CSS using the #content for function, such as
<% content_for :stylesheets do %> #navbar {display: none} <% end %> <%= render :template => "layouts/application" %>

You can also try this code with Online Javascript Compiler
Run Code
Then your application.html.erb layout must be configured to capture and utilize the material, for example, by adding the following #y
ield line:
... <head> ... <style><%= yield :stylesheets %></style> </head> ... render :template => "static_pages.html.erb" ...

You can also try this code with Online Javascript Compiler
Run Code
When you #yield to a specific content block, in this case:stylesheets, the code from that content for's block is dropped to where the #yield method was. So, in the preceding example, we introduced some CSS styling to the application layout by first producing specific static pages.html.erb layout and then sending the styles to the main application.html.erb layout using #content for.
Metaprogramming Rails
What exactly is "metaprogramming"? It's a fantastic and helpful notion utilized across Rails, and you can put it to use yourself. It's simply the concept that your programme or script may construct functions, methods, or classes on the fly while running and then call them dynamically. It's one of the beautiful things about using an interpreted language like Ruby... it's baked in. We'll only scratch the surface here, but if you're familiar with the nuts and bolts of Rails, you should delve into it more on your own.
The route helpers are an example of metaprogramming at the action in Rails. When your Rails application is launched for the first time, it reads the config/routes.rb file, which may contain the line get "home" => "static pages#home" so that your users may return to the home page by typing http://www.yoursite.com/home. Rails will then generate a few methods for you, including the home path and home URL helpers. That is a component of metaprogramming!
The routes example is almost unfair because you presumably built your routes.rb file and hardcoded a bunch of #home path or #home URL method calls based on what you expected to be in there. What about more dynamic scenarios in which you don't know what the technique will be called ahead of time?
To save the day, Ruby provides the #send function. If you want to perform a method on an object, pass the method and any arguments you want to that object. 1+2 is a basic example you may try on your command line:
> 1 + 2 => 3
> 1.send(:+, 2)
=> 3

You can also try this code with Online Javascript Compiler
Run Code
In most cases, there's no reason to utilize the #send method, but it's a lifesaver if you don't know which method you'll need to call. Provide the symbolic name of the method you wish to invoke on that object, and Ruby will search for it.
But, in any case, how can you define a new method on the fly? In this scenario, you can use the #define method, which accepts a symbol and a block containing the method itself.
Design Patterns
Among software engineers, design patterns have a mixed reputation. On the one hand, they reflect "best practices" for coding past a specific circumstance (not the particular code part, just a template for how to fix something). On the other hand, they might be too prescriptive. For a general summary, see the Design Patterns page on Wikipedia. This course will not discuss specific patterns.
The Wikipedia page on SOLID includes a solid summary and connections to SOLID software design resources. If you want to develop outstanding code, you must understand each of the ideas represented by the letters (paraphrasing):
- Principle of Single Responsibility (A class should only have a single responsibility)
- Principle of Open/Closed (your code entities should be open for extension but closed to modification)
- The Liskov Substitution Principle: It states that replacing an object with one of its subtypes should not cause any problems.
- Interface Segregation Principle (creating multiple client-specific interfaces is preferable to building one massive general-purpose interface... consider APIs)
- Principle of Dependency Inversion (instead of high-level constructs depending on lower level ones, make them rely on abstractions instead)
Fortunately, Rails has done a decent job of following principles, so you should have picked up some excellent habits just by using them. But you should read up on each of them (including the odd-sounding ones) because they're quite important to any software programming (and a ripe interview question).
I18n: Internationalization
The process of customizing your application to specific locations and languages is known as internationalization and localization. It's outside the scope of this article. However, for those who are interested, K. Bates recommended this Sitepoint lesson.
Career Opportunities in Ruby on Rails
Ruby on Rails has several tools which include less coding and more creativity. Developers will enjoy experimenting with the tools that will give anchors to new ideas and enhance them. In this framework, there is an independence of using new layouts and therefore it increases the horizon of learning new things along with giving utmost satisfaction in the career.
There is a huge demand and competition in the market for developers who have fluency in trending programming languages. And surprisingly, the developers who have mastered the framework of Ruby on Rails get a bigger package than any other developer. So, it is a good career option for people who are planning to jump into the application and development field. Ruby on Rails is gradually becoming one of the most popular web app frameworks. At this rate, the demand for RoR developers is going to increase indelibly. Many firms like Scribd, Twitter, eBay, etc. have already made the most of this technology and are quite satisfied with the results. Similarly, smaller organizations are preparing to switch and join the RoR fan crowd.
It literally pays to know Ruby on Rails. This can be justified very well because according to Indeed, the average salary for RoR is higher than 86% of the average salaries of other companies. This is pretty impressive for a decade-old technology. We can only imagine the number of career options it has opened up for the youth. Developers of RoR get paid more even for entrance-level posts. This is also because of the fact that the Ruby on Rails framework works on an open source dais, the companies don’t have to invest a lot in this technology.
Frequently Asked Questions
What is the role of Active Record in Ruby?
Its primary objective is to make sure that the relationship between the object and the database is maintained and that all validations are completed on time.
What are strong parameters? Explain in brief.
Many Rails projects use Strong Parameters, also known as Strong Params, to improve the security of data submitted via forms. Developers can utilize strong parameters to regulate which parameters are accepted and used by the controller. Any unnecessary or possibly dangerous parameters will be disregarded and properly filtered out by permitting just the anticipated parameters.
What is the object relationship model in Ruby on Rails?
In Ruby, false is a FalseClass object representing a boolean value, whereas Nil is a. The same clearly reveals that all classes are mapped to the systems in the smallest amount of time feasible, and the greatest part is that users are free to keep up the pace in the long term. It also indicates that the classes are associated with the rows and tables.
Conclusion
This article extensively discussed Advanced concepts of Ruby on Rails, including resources, management of routes, its redirection and design pattern. We hope this blog has helped you enhance your knowledge relating to Ruby on Rails.
Also check out - Strong Number
Check out our Ruby Vs Ruby on Rails, Ruby on Rails for Web Dev Projects, and All about Ruby on Rails articles. Practice makes a man perfect. To practice and improve yourself for the interviews, you can check out Top 100 SQL problems, Interview experience, Coding interview questions, and the Ultimate guide path for interviews. Do upvote our blog to help other ninjas grow. Happy Coding!
