Saeloun Blog

https://blog.saeloun.com/

Ruby on Rails and ReactJS consulting company. We also build mobile applications using React Native

フィード

記事のアイキャッチ画像
Enhancing Data Integrity With validate_foreign_key In Rails
Saeloun Blog
Rails offers powerful tools for managing database relationships, including the use of foreign key constraints.Foreign keyForeign key constraints establish a relationship between two tables in a database, ensuring that the value in a column (the foreign key) in one table matches a value in the primary key column of another table. This relationship helps maintain referential integrity, preventing orphaned records and ensuring data consistency.BeforeLet’s assume we’re building an application that stores articles and their respective authors.We’ll have two models, Article and Author.In case of relational DB, these are linked via foreign_keys.Each article is linked to its respective author using a foreign key. This setup allows us to easily retrieve all articles associated with a particular author by querying the articles table using the foreign key.add_foreign_key(from_table, to_table, **options)Let’s add foreign key to link each article to the authoradd_foreign_key :articles, :authorsThe
3日前
記事のアイキャッチ画像
Rails Adds GitHub CI Workflow By Default To New Applications
はてなブックマークアイコン 1
Saeloun Blog
Continuous Integration/Continuous Deployment, also known as Continuous Delivery or CI/CD, is a software development technique that aims to automate the steps involved in integrating code changes into a shared source code repository, testing those changes, and automatically deploying those changes to target environments without the need for human intervention.It makes early error detection easier and minimises the amount of code that needs to be debugged by a developer to identify the fault’s source.It also forms the basis of contemporary DevOps operations, facilitating more fluid and agile collaboration between development and operations teams.Several well-known CI/CD solutions include AWS CodeDeploy, GitHub CI, GitLab, TeamCity, Bamboo and Jenkins.GitHub CI/CDGitHub Actions is a powerful CI/CD tool provided by GitHub that gives developers the ability to automate their processes to build, test, and release software. It provides customizable CI/CD starter workflows that are suited for d
9日前
記事のアイキャッチ画像
ActiveRecord::Base#pluck adds support for hash values in Rails 7.2
Saeloun Blog
In day-to-day life, we see many dashboards which consist of charts and reports.To build these charts or reports quickly, we required specific data fromdifferent database tables in faster queries.The ActiveRecord::Base#pluck method is used to query single or multipleattributes from the database without loading the entire record.It returns the results as an array of attribute values.User.pluck(:id, :name, :email)The above code will result in the following query:SELECT users.id, users.name, users.email FROM "users"The above query returns the following output:=> [ [1, "David Heinemeier Hansson", "[email protected]"], [2, "Rafael França", "[email protected]"], [3, "Vipul Amler", "[email protected]"] ]BeforeWe are not limited to querying fields from a single table,we can query multiple tables as well.While we can use the column names as a symbol it used to only workwhile fetching columns from a single table,but when we wanted to join multiple tableswe had to go back to the string format to mention
15日前
記事のアイキャッチ画像
Enhancing Rails Log Output with SQL Query Count
Saeloun Blog
Rails developers often faced challenges optimizing performance due to logs that lacked detailed SQL query information.This made it difficult to identify specific performance bottlenecks, as the logs only provided general data on database interactions and view rendering times.A recent update to the Rails framework, offers an insightful enhancement to how Rails logs SQL queries during template rendering.This feature is particularly useful for developers who need to monitor SQL queries to optimize performance and debug issues efficiently.BeforePrior to the implementation of this feature, Rails logs displayed basic metrics about the requests processed, including total time, view rendering time, and database interaction time.However, they lacked detailed information about the count and type of SQL queries executed.Let’s take a code snippet to understand the behavior betterdef index @users = User.includes(:products).where.not(products: { id: nil })endThe typical log output for the above code
17日前
記事のアイキャッチ画像
A Quick Guide to Ruby's Time and DateTime Classes
Saeloun Blog
IntroductionRuby has three main classes for handling date and time: Date, Time, and DateTime.The DateTime class is a subclass of Date and is used to handle date, hour, minute, second, and offset.However, The Ruby documentation also recommends using the Time class instead of DateTime.The DateTime class is still available in Ruby for backward compatibility, but developersare encouraged to use the Time class for new projectsand to migrate existing code to use the Time class.DateTime in RubyDateTime in Ruby is a class that can handle date, hour, minute, second, and offset. It is a subclass of the Date class. The DateTime class can be used to represent a specific point in time with a specified offset from UTC.require 'date'datetime = DateTime.new(2023, 1, 1, 12, 0, 0, '-05:00')# <DateTime: 2023-01-01T12:00:00-05:00 ((2459946j,61200s,0n),-18000s,2299161j)In the above example, we are using the new method, passing in theyear, month, day, hour, minute, second, and offset as arguments.An offset
22日前
記事のアイキャッチ画像
Rails 8 adds Rubocop by default to new applications
Saeloun Blog
RuboCop is a static code analyzer also linter and code formatter for the Ruby programming language.It will enforce the guidelines outlined in the communityRuby Style Guide.It helps developers in ensuring adherence to coding style standards, identifying potential code flaws,and enhancing the overall quality of the codebase.In addition to identifying code problems, RuboCop also automatically corrects those issues.Developers can adjust rules defined by Rubocop to match project coding standards.Before Rails 8.0Before Rails 8 we had to manually integrate Rubocop gem to our project.We can simply install it like below.gem install rubocopor we can add it to the gemfile of the project.gem 'rubocop', require: falseThe behavior of RuboCop can be controlled via the .rubocop.yml configuration file. We can create this file manually and we can put it in the root of our project folder.Or we can run the below command that will automatically create the rubocop.yml and rubocop.todo.yml file.It is a good
1ヶ月前
記事のアイキャッチ画像
Rails 8 Adds Rate Limiting to Action Controller via Kredis Limiter Type
Saeloun Blog
Let’s understand what is Rate LimitingRate limiting is a technique used to control the rate of incoming requests or traffic to a server,API, or service. It helps in limiting the rate at which requests are processedwhich ensures system security and performance.By restricting the rate of requests made by individual clients or IP addresses, helpsin preventing abuse, such as denial-of-service attacks or brute-force login attempts.Now question is how to do this in Rails.Before Rails 8.0Before Rails 8 there were different ways to implement rate limiting that depends onspecific requirements and constraints.One such way of it is by using rack-attack gem.To use this gem, we need to create a new file config/initializers/rack_attack.rb andthen we can write rate limiting rules in this file.For example, if we want to block access to all admins we can define rules in the following way:# config/initializers/rack_attack.rbRack::Attack.blocklist("block all access to admin") do |request| # Requests are
1ヶ月前
記事のアイキャッチ画像
Rails 8 adds allow_browser to set minimum browser version
Saeloun Blog
Browser compatibility is critical for ensuring that a website displays and performs properly across several web browsers.Every browser renders code differently,thus compatibility testing is critical for reaching a larger audience.It involves evaluating how a website appears in several browsers such as Chrome,Firefox,Safari,andInternet Explorer.As the number of mobile users grows,interoperability with mobile platforms becomes increasingly important.BeforeBefore Rails 8,browser compatibility was detected using the browser gemgem "browser"To detect whether a browser can be considered as modern or not,we create a method that abstracts our versioning constraints.def modern_browser?(browser) [ browser.chrome?(">= 65"), browser.safari?(">= 10"), browser.firefox?(">= 52"), browser.ie?(">= 11") && !browser.compatibility_view?, browser.edge?(">= 15"), browser.opera?(">= 50"), browser.facebook? && browser.safari_webapp_mode? && browser.webkit_full_version.to_i >= 602 ].any?endAfterRails 8 will in
2ヶ月前
記事のアイキャッチ画像
Rails 7.1.2 now ignores implicitly passed locals in templates that use strict local definitions
Saeloun Blog
Templates have always been a powerful way to organize and reuse view elements. Rails 7.1 introduced strict local definitions in templates. This means that templates can now define a strict list of locals that they accept. This is useful for catching typos and other errors.For example, to render a profile card with strict locals, a template might look like this:# app/views/_profile.html.erb<%# locals: (name:, avatar:) -%><div> <%= image_tag avatar %> <%= name %></div>The magic comment locals: (name:, avatar:) defines the locals that this template accepts. If a local that is not defined is passed to this template, an exception will be raised.# app/views/homepage/index.html.erb<%= render partial: 'profile', locals: { name: user.name, avatar: user.avatar, address: user.address } %>Since address is not defined in the template, this will raise an exception.ActionView::Template::Error (unknown local: :address):app/views/homepage/index.html.erb:2BeforeTemplates can also be used to render colle
2ヶ月前
記事のアイキャッチ画像
Rails 8 adds Brakeman by default to new applications
Saeloun Blog
What is Brakeman?Brakeman is a security scanner for the Rails application. It statically analyzes the source code and looks for security issues at any stage of development.Brakeman requires no configuration, once it is installed, we can just run it.It scans the application code and produces a report of all the security issues it has found.Brakeman helps in early security issues detection, Developers are better aware of any security vulnerabilities with the help of Brakeman.It can identify a wide range of security vulnerabilities like SQL injection, Cross-site scripting(XSS), and Cross-site request forgery(CSRf).It also checks for code that allows users to bypass security checks and gain unauthorized access and many more.By default Brakeman reports as much as possible because it doesn’t know if certain values are safe or not, it can lead to many false positives.But it provides option to customize the report and also we can ignore specific warnings to reduce false positives.To start the
2ヶ月前