Summary of Ruby on Rails fundamental concepts

前端 未结 2 1666
臣服心动
臣服心动 2021-01-29 17:52

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

2条回答
  •  故里飘歌
    2021-01-29 18:40

    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

提交回复
热议问题