Basic mistakes when programming Rails

Tram Ho


Rails is a widely used open source framework in the world, built on the Ruby programming language with the criteria to simplify the process of web application development. However, the simpler the more, the more subjective it is for programmers and sometimes there are mistakes that they did not anticipate. Sometimes errors occur that the programmer himself cannot understand what is going on and is extremely frustrating. Those problems can be security or performance issues, but of course all of this has to be fixed. This article will list the 10 common mistakes that programmers make, and how to limit them.

1. Handling logic too much in controller

For those who have been working with Rails for a while, it is probably not new to the rails MVC system and the phrase “fat model, skinny controller”. This means that every business logic will be in the Model, the Controller is only responsible for coordinating and handling the simple logic between M and V. If there is too much logic inside the controller, it will be difficult to change later if we need any more logic. Even this also violates the single responsibility principle – A class should only hold one responsibility only (Can only modify the class for only one reason). Using too much logic in the controller makes future code editing difficult and error-prone. In general, only the following functions and logic code should be present in your controller:

  • Session and cookie control: It may also include authentication / authorization logic or any additional cookie processing you need to perform.
  • Model selection: The logic for finding the right model for the params passed from the request. Ideally, call a method to set an instance variable that will be used later to return.
  • Manage request params: Summarize the params and call an appropriate model method to handle them.
  • Rendering / redirecting: Display the result (html, xml, json, etc.) or redirect, if needed.

2. Handling logic too much in view

The Rails ERB templating system is a great way to build pages with content variables. However, if you are not careful, the result will be a huge file with a messy combination of Html and Ruby code, making editing and maintaining extremely difficult. And certainly if you put a lot of logic in the view, then compliance with the DRY rule will be broken. For example, instead of always having to check whether the current_user exists or not to display the name, if not then display the Guest:

It is always possible to set a default for the name = Guest if current_user does not exist in application_controller

This function will allow you to replace the above code with a simple command line as follows:

2 important notes when writing views in rails:

  • Ensure encapsulate, we should use layout and partial.
  • Use presenters / decorators to encapsulate the logic in the view into an object, from which we can use these objects without writing the logic in the view.

3. Processing logic too much in the model

Besides putting lots of logic in views and controllers, developers deal with a lot of logic in the model which leads to terrible maintenance. Functions such as creating email notifications, linking to external services, conversion to other data formats, and functions that do not have much to do with the model’s primary responsibility should be given low priority. rather than finding and maintaining data in a database. So if not in the controller, not stopping at the view nor being able to stay in the model, where should the logical code go? (sounds pretty sad for logic code). But fortunately, the answer is POROs * (plain old Ruby objects). With a comprehensive framework like Rails, new developers will often hesitate to create their own classes that are not part of the framework. However, removing logic from a model and moving it to POROs is often recommended to prevent the Model from becoming too complicated. With Poros, you can package things like email notifications or API interactions into separate classes rather than pairing them into an ActiveRecord model. With the above in mind, only the following logical code should exist in your Models:

  • ActiveRecord configuration. For example, relation, validate …
  • Business logic that manipulates the database such as adding or removing errors …
  • Query, you should only use queries like where in the model, not in controller or view.

4. Indiscriminate use of helper

Rails places emphasis on named components (model, view and controller). This is pretty good when defining something that belongs to classes of these components. But sometimes we may need functions that do not belong to the model, view or controller. The Rails generator function creates a helper directory and a new helper class with each component we create. It’s like encouraging us to cram any functionality that doesn’t fit the model, controller or view into these helper classes. When you have an additional function, think about grouping functions together and finding a really clear name for the class that will store these functions. Using a comprehensive framework like Rails is not an excuse for indiscriminate use of functions and classes.

5. Using too many Gem

Ruby on rails is very much supported by an extremely rich amount of Gem, it helps programmers handle complex problems very easily through installing gems rather than adding complex logic. into the project. However, there are also a lot of cumbersome applications with countless gems used in it while the functions that the application brings are not commensurate with the number of gems used. This leads to some problems of Rails:

  • Using multiple gems makes our application heavier than necessary and of course affects performance, consumes ram and of course increases the cost of the system. Start slowly, load slowly, and when running automation tests also slow.
  • Each gem you install will usually install some gem dependency. For example, if you install rails_admin gem, you have already installed 11 additional gems that come with it.

6. Skip the log files

Most programmers probably know the log files are stored in the log directory for each development or production environment. Rails provides you with many useful functions, especially in the model. Clearly defining the associations in your model will make it easier to use data relationships even when used in views. All the basic SQL parts needed for your model are automatically Rails. That’s great, but how can you be sure these SQL parts are really effective? One SQL error that you frequently make is the N + 1 query error. For example, you need a query to display all the comments of a post:

Looking at the log after performing the above function, we will see a query to retrieve 3 posts then continue to be 3 queries to retrieve the comments of each post:

Active Record in Rails can significantly reduce the number of queries by allowing you to specify in advance all necessary parts to be called. This is done by calling the include (or preload) method on ActiveRecord :: Relation. With include, AvtiveRecord will ensure all necessary parts are loaded with the minimum number of queries possible. For example:

When the code was revised as above, the log showed us that all the comments were retrieved with just one query instead of the previous three:

That’s just an example of a n + 1 query problem. Obviously, the log reading helps us to review and check if the system works smoothly or not.

7. Skip automated testing

Rails provides extremely powerful and efficient automated testing. Many Rails developers use TDD and BDD types to write very sophisticated test suites, they also give us extremely powerful testing frameworks with gems like rspec or cucumber. They are all very easy to use but many people skip this important step.

8. Block access from external services

Third-party services are usually very easy to use and integrate into the rails application, but it does not always work smoothly and quickly or even make mistakes on their part. If this is not careful, it will slow down our application or sometimes delay or server dead. To avoid blocking the request instead of invoking the service directly during the processing of a request. You should move them back to the background job queue to execute when possible.

  • Delayed job
  • Resque
  • Sidekiq: if you do not want to use the background job, make sure that the code is in error handling, and try to turn off the network running locally to see if there is no 3rd party connection, your application will have problems.

9. Don’t want to change old database migration files

Rails records the current database structure through the file db / schema.rb and it is always updated every time you update the migrate. Because these migration files are named sequentially, you can run them from scratch to create an empty database. This is a great way to manage small changes in the application’s database and avoid Rails issues. Over time, the database creation process can take quite a bit of time, sometimes the order is accidentally changed or lost, such as a file migration migration or being inserted from an application. Other rails use the same server database. Rails will describe your current database schema in the shema.rb file after each database update. This file can be created when there is no change in the database just by running the db: schema: dump command. A common mistake made by many developers is to create a new migration into your application without updating the corresponding schema file. When migrations are out of control and it takes too much time to run or no longer create the database properly, the programmer should not be afraid to delete old migration files, create a new schema, and continue from there.

10. Revealing sensitive and important information is confidential

Rails provides very good security support tools to avoid being attacked in many ways. One of them is to use app_secret to protect the browser session. Although this token is stored in config / secrets.yml and for the production environment, this file reads information from environment variables. With the old version of rails, it was written in config / initializers / secret_token.rb and this file is often mistakenly posted to code management tools like other files for everyone to see and this is invisible. same danger. So you need to put this file in .gitignore to restrict outsiders to see and retrieve information.

Share the news now

Source : Viblo