| name | coding-in-ruby-on-rails |
| description | Follow these rules while coding in ruby on rails. |
Follow these rules strictly when coding in Ruby on Rails to ensure a maintainable, high-performance, and secure codebase.
1. Backend changes: schema and model first
- Before changing anything in the backend: For every table or ActiveRecord model your work touches, read that table's definition in
db/schema.rb (or the relevant migration if the schema file is not authoritative), then read the matching model file. Complete this step before you edit controllers, services, jobs, serializers, views, routes, tests, or any other backend code. Treat those files as the source of truth for columns, types, indexes, associations, and validations.
2. General Rails Structure
- Follow Rails Conventions: Adhere strictly to the standard MVC architecture and Rails directory structure. Follow rails convention while writing code.
- The Rails Way: Use built-in Rails features (helpers, callbacks, etc.) before implementing custom solutions.
3. Fat Models & Skinny Controllers
- Skinny Controllers: Controllers should only handle requests (params, authentication, session) and responses (rendering, redirection). Business logic must not reside in controllers.
- Fat Models: Business logic, complex validations, and data transformations belong in models. If a method can be used multiple times or contains complex logic, it must reside in its suitable model.
- Scopes: Use model scopes for common database queries to keep logic reusable and readable.
- Query Objects: For complex queries involving multiple tables, use Query Objects.
4. Service Objects
- Business Workflows: Use Service Objects (e.g.,
app/services) for operations that involve multiple models or complex third-party integrations.
5. API Responses (Jbuilder)
- JSON.Jbuilder: Always use
.json.jbuilder files for crafting API responses. Do not render JSON directly in controllers.
- Decoupling: Keep the response structure separate from the controller logic.
- Explicit Render: If a controller uses
json.jbuilder, always explicitly call render at the end of the controller action to show which file is getting rendered (e.g., render :show or render 'users/show').
6. Performance (N+1 Prevention)
- Eager Loading: Always use
.includes, .preload, or .eager_load to prevent N+1 query issues.
- Bullet: Utilize tools (like the Bullet gem) during development to catch N+1 queries early.
7. Security & Parameters
- Strong Parameters: Strictly use
params.require(...).permit(...) to prevent mass assignment vulnerabilities.
- Sanitization: Never trust user input. Use Rails' built-in sanitization and escaping.
8. Coding Style & Naming
- Standard Conventions: Use
snake_case for methods and variables, and CamelCase for classes/modules.
- Meaningful Names: Give variables and methods descriptive, intent-revealing names.
- Class Definition: use "class Corp::Api::HousieTeamRn::V1::StoreManager::PackersController < Corp::Api::HousieTeamRn::V1::StoreManager::BaseController" instead of nested modules
9. Database & Migrations
- Indexing: Always add database indexes for foreign keys and frequently queried columns to ensure performance.
- Immutable Migrations: Never modify an existing migration file after it has been pushed. Always create a new migration to make changes.
10. Routing
- RESTful Routes: Stick to standard RESTful resources (
resources :users) and avoid custom actions when possible.
- Shallow Nesting: Avoid deep nesting of routes. Use
shallow: true or break nested resources into their own top-level resources if nesting exceeds 1 level.
11. Background Jobs
- Async Processing: Offload long-running tasks (e.g., sending emails, data processing, external API calls) to background jobs using ActiveJob.
12. Testing
- Coverage: Write tests for critical paths, models, and services.
- Factories: Use FactoryBot for test data generation instead of fixtures for better maintainability.
13. Error Handling
- Centralized Handling: Use
rescue_from in ApplicationController to handle common exceptions (like ActiveRecord::RecordNotFound) and return consistent JSON error responses.
14. Maintainability (Callbacks)
- Avoid Callback Hell: Avoid placing complex business logic in ActiveRecord callbacks (
before_save, after_create). Use Service Objects to handle flows that require multiple steps to prevent side-effect loops and hard-to-debug logic.