Understanding Ruby On Rails
Phase 4 notes
After working on Ruby throughout Phase 3 of my flatiron boot-camp, I was eager to get started on the ruby framework, Rails.
Rails Generators:
Attributes are default given a value of a string.
rails g migration CreatePets name breed –no-test-framework: creates migration file with desired attributes.
rails g model Pet name breed –no-test-framework; creates a model & migration file with desired attributes.
rails g resource Shop –no-test-framework ; creates a model, migration file, and routes with desired attributes.
rails db:migrate
To add a key value pair on an existing table:
rails g migration AddAgeToPets –no-test-framework
This will create an empty migration table which you could make to look like this,
Class AddAgeToPets < Active Record:: Migration
Def change
add_column : pets, :age, :integer
End
End
To update a key value pair on an existing table:
rails g migration ChangeAgeInPets –no-test-framework
Class ChangeAgeInPets < Active Record:: Migration
Def change
change_column : pets, :age, :string
End
End
To remove a key value pair on an existing table:
rails g migration RemoveAgeFromPets –no-test-framework
Class RemoveAgeFromPets < Active Record:: Migration
Def change
remove_column : pets, :age
End
End
If there was a mistake with a migration, use rails rollback.
To rollback a migration:
rails db:rollback
Seeds
Pet.create(name: “Timmy”, breed: “Siamese”)
Pet.create(name: “King”, breed: “Tabby”)
Pet.create(name: “Lucy”, breed: “Siberian”)
OR
Pet.create([{name: “Timmy”, breed: “Siamese”}, {name: “King”, breed: “Tabby”}, {(name: “Lucy”, breed: “Siberian”}])
Once set up, run
rake db:seed
then
rails console
Faker
To install, go to Gemfile and add:
gem ‘faker’
and then run bundle install
within seeds.rb
Pet.create(name: Faker::Creature::Cat.name, breed Faker::Creature::Cat.breed
Then
rails db:seed
The syntax used above can be found on the faker gem documentation.
Routes
Rest routes stand for Representational State Transfer. Bundles concerns with mapping HTTP methods to their associates CRUD actions.
Can individually write out each route as such:
Rails.application.routes.draw do
get ‘/birds’, to: ‘birds#index’
get ‘/birds/:id’, to: ‘birds#show’
end
OR WITH RESOURCE, WHICH INCLUDES ALL REQUEST TYPES
def
resource :pets, only: [:index, :show]
end
Validators
Validators are written within the projects Model files.
They are used to ensure no bad data ends up in our database, as well as allows us to manipulate the error messages in order to display on the front-end easier.
Ex:
class Person < Active Record::Base
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :email, uniqueness: true
validates :password, length: { in: 6..20 }
validates :registration_number, length: { is: 6 }
end
Or
class Person
validate :must_have_flatiron_email
def must_have_flatiron_email
unless email.match?(/flatironschool.com/)
errors.add(:email, “We’re only allowed to have people who work for the company in the database!”)
end
end
end
An example of validators being used in the Controller to manipulate error messages:
def create
person = Person.create(person_params)
if person.valid?
render json: person, status: :created
else
render json: { errors: person.errors.full_messages }, status: :unprocessable_entity
end
end
Error handling is extremely important & useful for any sort of back-end development. Being able to efficiently return and error: object that identifies where the user’s invalidation is occurring is extremely useful.
Project Notes
Phase 4 dived in depth into Ruby on Rails. Rails is a web framework, a ruby gem, and an MVC framework into one.
MVC stands for model, view, controller. MVC is a popular application architecture that helps developers naturally separate concerns and organize their applications properly.
MVC or CMV:
Model: The model is the chef. It manages the critical aspects of the application, such as communicating with the database via Active Record. One of our favorite tasks in a Rails application is working with the model files. This is where you can be very expressive with the custom algorithms that you want to utilize and you also have direct access to the specific database record. The logic of your application should mainly reside in the model files.
A app/models/article.rb model file that will contain: validations, database relationships, callbacks, and any custom logic for articles.
Controller: The controller is the waiter. In the same way that the waiter takes the order from the customer to the chef and then brings the food to the table, the controller transmits data requests from the user to the model, and then delivers data that is rendered in the view to the user.
A app/controllers/articles_controller.rb file that will have methods to manage data flow for the article behavior, including the full set of CRUD features. The standard methods are: index, create, show, update, and destroy.
View: The view is the table. A table shouldn’t do anything besides sit there and hold the food when it is delivered. In like manner the views should not contain any programming logic, they should simply render what the controller sends them. In a Rails API application, our view layer will consist of the JSON data that is returned from our controllers.
A app/views/articles directory that will contain a corresponding view for each of the pages that the end user will access. Note: in a Rails API application, we won’t have a dedicated folder for our views like we would in a typical Rails MVC application.
Make sure Rails gem is installed: <gem install rails>
Create new Rails project <rails new project-name — skip-javascript>
Rails File Overview
· app: contains the Models, Views, and Controllers, along with the rest of the core functionality of the application. Most of your time will be spent working in this directory.
· bin: some built-in Rails tasks that you most likely will never have to work with.
· config: the config directory manages several settings that control the default behavior, including: the environment settings, a set of modules that are initialized when the application starts, the ability to set language values, the application settings, the database settings, the application routes, and lastly the secret key base.
· db: within the db directory you will find the database schema file that lists the database tables, their columns, and each column’s associated data type. The schema file can be found at db/schema.rb. The db directory also contains the seeds.rb file, which lets you create some data that can be utilized in the application. This is a great way to quickly integrate data in the application without having to manually add records through a web form element.
· lib: while many developers could build full applications without ever entering the lib directory, you will discover that it can be incredibly helpful. The lib/tasks directory is where custom rake tasks are created. You have already used a built-in rake task when you ran the database creation and migration tasks; however, creating custom rake tasks can be very helpful and sometimes necessary. For example, you could create a custom rake task that runs in the background, making calls to an external API and syncing the returned data into the application’s database.
· log: within the log directory you will discover the application logs. This can be helpful for debugging purposes, but for a production application it’s often better to use an outside service since they can offer more advanced services like querying and alerts.
· public: this directory contains some of the custom error pages, such as 404 errors, along with the robots.txt file which allows you to control how search engines index the application on the web.
· test: by default Rails will install the test suite in this directory. This is where all of your specs, factories, test helpers, and test configuration files can be found.
· tmp: this is where the temporary items are stored and is rarely accessed by developers.
· vendor: a folder for third-party code, such as code for JavaScript plugins and CSS frameworks.
· Gemfile: the Gemfile contains all of the gems that are included in the application; this is where you will place outside libraries that are utilized in the application. After any change to the Gemfile, you will need to run bundle install. This will download all of the code dependencies in the application. The Gem process can seem like a mystery to new developers, but it is important to realize that the Gems that are brought into an application are simply Ruby files that help extend the functionality of the app.
· Gemfile.lock — this file should not be edited. It is created when you run bundle install and it displays all of the dependencies that each of the Gems contain along with their associated versions. Messing around with the lock file can lead to application bugs due to missing or altered Gem dependencies.
· README.md — the readme file is an important place to document the details of the application. If the application is an open-source project, this is where you can place instructions to other developers, such as how to get the app up and running locally.
Start up the Rails server by running command <rails s>
Now would be a good time to set up the front-end client with React.
In the terminal, enter <npx create-react-app client –use-npm>
Then, within package.json
In order to not have to enter localhost:3000 for fetch requests and just enter /productions, right under private:true. enter
“proxy”: “http://localhost:3000",
Also, within the “start” script, add PORT=4000, in order to differentiate ports for the front & backend.
Then, cd into the client, and run npm start in order to fire up the front end.