iwasrobbed
iwasrobbed

Reputation: 46703

Summary of Ruby on Rails fundamental concepts

Being new to Rails, I am having a difficult time finding a website or reference that gives a run down summary of Ruby on Rails. I understand MVC, ActiveRecord, and that sort of stuff on a basic level, but I am having a hard time understanding some of the relationships and fundamentals. For instance:

  1. What are all naming conventions I need to be aware of?
  2. How should controller actions be structured and named?
  3. What are the best ways to render information in a view (via :content_for or render a partial) and what are ways I shouldn't use?
  4. What should go into a helper and what shouldn't?
  5. What are common pitfalls or something I need to do correctly from the very beginning?
  6. How can you modularize code? Is that what the lib folder is for?

I have read a number of responses on StackOverflow in regards to this question, but all of them just point to a 300+ page book I need to read, whereas I just want a concise summary of what's important.

Some resources I am already aware of, but do not offer a concise summary of fundamental concepts for new users:

Thank you for any help, references, or guidance you can provide!

P.S. I would like this wiki to become a living document, so please add to it, edit it, etc. as you feel necessary.

Upvotes: 49

Views: 18744

Answers (3)

Chat GPT answers:

Understanding Ruby on Rails and its conventions can indeed feel overwhelming at first, but once you get familiar with its principles, it becomes much easier to navigate. Let’s break down your questions to provide a clearer view.

1. Naming Conventions

  • Models: Singular and CamelCase (e.g., User, ProductCategory). Database tables should be pluralized (e.g., users, product_categories).
  • Controllers: Plural and CamelCase, ending in Controller (e.g., UsersController, ProductCategoriesController).
  • Views: Organized into folders matching controller names (plural), with file names matching action names (e.g., users/show.html.erb for the show action in UsersController).
  • Migrations: Prefixed with a timestamp and describe the action taken (e.g., 202401011230_add_email_to_users.rb).

2. Controller Actions Structure and Naming

Rails follows RESTful conventions, suggesting the use of seven standard actions where applicable: index, show, new, create, edit, update, and destroy. Structure your controllers around resources and keep actions RESTful when possible, focusing each action on a specific CRUD operation.

3. Rendering Information in Views

  • Using render for Partials: Ideal for reusable components (e.g., forms, sections of a page). Name partials with a leading underscore (_form.html.erb) and render them with render 'form' or render partial: 'form'.
  • Using :content_for: Best for inserting content into specific areas of a layout from within a view, like adding a custom title or scripts. Avoid overusing content_for for content that fits naturally into a partial structure.
  • Not Recommended Practices: Overusing helper methods for generating HTML (leads to cluttered helper modules) and placing too much logic in views (consider moving complex logic to helpers or presenters).

4. Helpers

Helpers are intended for view-related methods to keep the view code clean and readable. Examples include formatting dates, numbers, or strings, and generating form components or links. Avoid putting business logic in helpers; that should reside in models or service objects.

5. Common Pitfalls

  • Not Following RESTful Principles: Leads to confusing controller actions and routes.
  • Fat Models or Controllers: Strive for skinny controllers and models; use service

Upvotes: 0

Daniel Garcia
Daniel Garcia

Reputation: 1402

I wrote some naming conventions some time ago:

Rails conventions

General

All filenames are in snake_case following the same conventions - Model: singular (e.g. Restaurant) - Controller: plural (e.g. RestaurantsController) - Table in DB: plural (e.g. restaurants) - URL's: all in plural (e.g. /restaurants, /restaurants/:id, /restaurants/new)

rails generate Commands

  • Create model: singular (because the name of the model is singular). e.g. rails g model Restaurant name:string rating:integer
  • Create migration: plural (because we use the name of the table). e.g. rails g migration AddDescriptionToRestaurants description:text
  • Create controller: plural e.g. rails g controller Restaurants index show

Model (singular)

ActiveRecord methods

All in singular, because all ActiveRecord's methods are linked to the model. Examples: - Restaurant.all - Restaurant.create(name: "Burger King", rating: 2) - Restaurant.find(params[:id])

Associations

  • Singular in the belongs_to. Because it belongs to one element.
  • Plural in the has_many. Because it has many elements.

e.g.

class Restaurant < ActiveRecord::Base
  has_many :reviews
end

class Review < ActiveRecord::Base
  belongs_to :restaurant
end

Routes

Resources

Plural when defining a route for a resource:

resources :restaurants

Route helpers

  • index: plural (because we are showing a list of elements). e.g. restaurants_path. Can also be used used for create.
  • show: singular (we are showing just one element, it needs the element inside parenthesis). e.g. restaurant_path(@restaurant). Can also be used for update & delete.
  • new: singular. e.g. new_restaurant_path

Upvotes: 7

Matt Briggs
Matt Briggs

Reputation: 42158

1. What are all naming conventions I need to be aware of?

db table is plural, model is singular, controller is plural. so you have the User model that is backed by the users table, and visible through the UsersController.

files should be named as the wide_cased version of the class name. so the FooBar class needs to be in a file called foo_bar.rb. If you are namespacing with modules, the namespaces need to be represented by folders. so if we are talking about Foo::Bar class, it should be in foo/bar.rb.

2. How should controller actions be structured and named?

controller actions should be RESTful. That means that you should think of your controllers as exposing a resource, not as just enabling RPCs. Rails has a concept of member actions vs collection actions for resources. A member action is something that operates on a specific instance, for example /users/1/edit would be an edit member action for users. A collection action is something that operates on all the resources. So /users/search?name=foo would be a collection action.

The tutorials above describe how to actually implement these ideas in your routes file.

3. What are the best ways to render information in a view (via :content_for or render a partial) and what are ways I shouldn't use?

content_for should be used when you want to be able to append html from an inner template to an outer template -- for example, being able to append something from your view template into your layout template. A good example would be to add a page specific javascript.

# app/views/layout/application.rb
<html>
  <head>
    <%= yield :head %>
...

# app/views/foobars/index.html.erb

<% content_for :head do %>
  <script type='text/javascript'>
    alert('zomg content_for!');
  </script>
<% end %>

partials are either for breaking up large files, or for rendering the same bit of information multiple times. For example

<table>
  <%= render :partial => 'foo_row', :collection => @foobars %>
</table>

# _foo_row.html.erb

<tr>
 <td>
  <%= foobar.name %>
 </td>
</tr>

4.What should go into a helper and what shouldn't?

your templates should only have basic branching logic in them. If you need to do anything more intense, it should be in a helper. local variables in views are an abomination against all that is good and right in the world, so that is a great sign that you should make a helper.

Another reason is just pure code reuse. If you are doing the same thing with only slight variation over and over again, pull it into a helper (if it is the exact same thing, it should be in a partial).

5. What are common pitfalls or something I need to do correctly from the very beginning?

partials should never refer directly to instance (@) variables, since it will prevent re-use down the line. always pass data in via the :locals => { :var_name => value } param to the render function.

Keep logic out of your views that is not directly related to rendering your views. If you have the option to do something in the view, and do it somewhere else, 9 times out of 10 doing it somewhere else is the better option.

We have a mantra in rails that is "fat models, skinny controllers". One reason is that models are object oriented, controllers are inherantly procedural. Another is that models can cross controllers, but controllers cant cross models. A third is that models are more testable. Its just a good idea.

6. How can you modularize code? Is that what the lib folder is for?

the lib folder is for code that crosses the concerns of models (i.e. something that isn't a model, but will be used by multiple models). When you need to put something in there, you will know, because you wont be able to figure out what model to put it in. Until that happens, you can just ignore lib.

Something to keep in mind is that as of rails 3, lib is not on the autoload path, meaning that you need to require anything you put in there (or add it back in)

A way to automatically require all modules in the lib directory:

#config/initializers/requires.rb
Dir[File.join(Rails.root, 'lib', '*.rb')].each do |f|
  require f
end

Upvotes: 87

Related Questions