Why Ruby on Rails is one of the best first programming languages ​​for designers. What can you create with Rails? What is Rails


Today I found a story on the Internet about how someone named James Fend learned Ruby on Rails for 12 weeks. Below you can read a relatively accurate translation of this story, and hopefully be inspired to explore this wonderful framework (and wonderful language).

Before I begin, I'd like to introduce Josh Crews (http://joshcrews.com) and thank him for convincing me to start learning Ruby on Rails; without him, his help, and without the hours he spent being my mentor, I would not be writing this today. Thank you.

On January 23rd, I launched my dream idea, Freelancify.com. Exactly 12 weeks ago, I was a tech entrepreneur spending thousands of dollars to create a decent MVP (minimum viable product) because I lacked knowledge. One of the reasons (I thought at the time) was that the training was too difficult for me or would take an inordinately long time. I thought (like many others) that programmers are (and some are) born with a set of magical problem-solving and math skills that make them programming geniuses. And exactly 12 weeks ago I accepted The best decision for a long, really long time. No longer will any of my ideas remain anything more than an idea. Now I have the opportunity to launch production versions, spending money only on hosting and putting in some effort. Today, this skill set is akin to pulling a bunch of tractors during the California Gold Rush while everyone else was using simple shovels. I suggest everyone learn to write code. Here I would like to add a clarification: earlier, I called the post “How I learned Rails in 8 weeks,” however, to be precise, given the launch date, it turns out to be 12 weeks. However, within 8 weeks I felt I knew enough, and the next four weeks were spent more on putting the knowledge I'd gained to work rather than learning.

What skills did I have before I started learning Rails?

I was a web designer with knowledge of HTML and CSS and mainly focused on UI and UX design. The hardest thing I've done with actual code (not counting HTML) is being able to customize Wordpress. In short, I had absolutely no idea what an MVC framework was or how databases work in general. The design, layout and HTML for Freelancify were created by me in two weeks in June 2011.

Why did I decide to study?

Going back to June 2011, when the layout was ready, I began searching for a coder who would make the layout functional. The layout was almost ready: I ​​had text fields, drop-down menus, forms, buttons, links leading to where needed, and so on. I found a developer, and, in a nutshell, the guy didn’t suit me. I was left with a ton of debt and no product even close to being completed. So I contacted Josh Krius (I met him at a Ruby on Rails meetup he organized in Nashville) and met with him to see if I could make something of what I had left as a developer . Unfortunately, fixing and modifying the code would take no less time than developing it from scratch by a competent programmer. I became disheartened, realizing that I could not afford to spend thousands of dollars again on development from scratch. And then Josh said... “ Why don't you just learn how to handle Ruby on Rails, this project would be a great way" and then " I can even meet with you twice a week and help you with your studies" I spent the whole night thinking about it. My options were: find a comfortable job and pay the bills OR risk everything to learn Rails and ultimately feast on the best ramen Italy has to offer. I decided. I called Josh the next morning. I put everything. I allocated money from the remaining savings and divided it over three months (for a single guy living alone and without children, one thousand dollars per month is enough). Time to get to work, I am now a full time apprentice. Keeping in mind that Google search, Stackoverflow, IRC #RubyOnRails and the Rails community will have my back when I get stuck, I'm sure there will be plenty of them.

My next three months - Mission: Get an MVP, get enough to work, but not “suck-enough” to leave a terrible first impression.

Weeks 1 - 3

It was probably the biggest learning curve, but I did NOT give up.

Walls are made for people who don't really want to leave them.

Setting up a working Rails environment for a complete newbie can be incredibly annoying. Tip #1: Get a Mac. Tip #2: Use Homebrew, RVM, Git and Heroku (that's really all you need to get started). I spent a couple of days installing, then uninstalled everything and installed again. Just repeat it a few times and you will get used to using the terminal (console) command line and understand why things work the way they do. Then, the first thing I took up was TryRuby, Rails for Zombies, and Michael Hartle's Rails Tutorial. Don't worry about understanding the material 120%, it won't happen until you actually start studying. I finished the Rails Tutorial and created this similar to Twitter app in about a week, not really understanding what I had done. Later, as I progressed, I began to realize that everything was starting to make sense.

Weeks 3 - 6

With a Twitter app built using the Rails Tutorial, I gained some confidence. The tutorial didn't make me a developer, but I now know the general steps in creating apps, from creating the app itself to installing it on Heroku. Everything that happened in between remained blurry. How can I REALLY start studying now? Working on a real project that means something to me. Josh and I decided that I should freely work on Freelancify and see what I could do. The first thing I did was move all the HTML from the framework and organize it into views and partials files. I have created scaffolded template platforms for Users and Projects. Then I started learning my first real gem, Devise. Then, the ability to have relationships, for example, each User will have a portfolio. But Users can have multiple portfolios, while each portfolio can only belong to one User. Once you understand how relationships between models work and how to call/display things that belong to something else, life will become much easier. If you get stuck on a part and can't move, skip it, chances are that while you're developing another feature, you'll also figure out how to implement what you missed.

Weeks 6 - 9

Step by step, I continued to learn, copying and repeating. I would make some things work, and then - bam - and I would hit a wall and have absolutely no idea what to do next. Whether going on Stackoverflow, IRC chat #RubyOnRails, RailsCasts, or tugging at Josh, I eventually figured out how to proceed. Do the same thing over and over again and you'll get the hang of it pretty quickly. Spending annoying hours testing someone's answer on Stackoverflow only to realize it doesn't work is actually useful. You understand what not to do. And when you find the answer you will begin to understand WHY the latter didn't work. It was around this time that I began to realize how big the picture was of things and to truly understand WHY everything works exactly the way it works. I felt like an idiot and went back and refactored the code I had written earlier, making it more efficient. And at some point I reached a stage where everything started to fall into place.

Weeks 9 - 12

I was in incredible energy mode getting Freelancify to the launch stage. At this stage I felt as if I was flying, putting the functions into action. The last week was spent debugging various bugs and blunders. This Monday I launched the site. But I'm still far from completing my studies... That's it. I have omitted (in the name of brevity of the post) small details and technical points. However, feel free to ask questions in the comments, I will definitely try to answer. James Fend.

P.S. - While it helped a lot to have a mentor I could meet with, you can definitely learn Rails without one. Or try to find yourself such a person, many Rails developers love to contribute to the community. Look for local conferences and meetups.

This entry is already more than two years old (published on January 27, 2012), but, nevertheless, it has not lost its relevance. During this time, James Fend managed to sell Freelancify and invest in a new startup, he left a note about this on February 27, 2013. I believe that this article is an excellent example of how a person can achieve his goal. All you have to do is start. :)

This guide covers installing and running Ruby on Rails.

After reading it, you will learn:

  • How to install Rails, create a new Rails application, and attach your application to a database.
  • The general structure of a Rails application.
  • Basic MVC principles(Model, View Controller- "Model-View-Controller") and RESTful based design.
  • How to quickly generate initial code for a Rails application.

Assumptions in this manual

This tutorial is aimed at beginners who want to start a Rails application from scratch. It does not assume that you have worked with Rails before.

Rails is a web development framework written in the Ruby programming language. If you don't have experience with Ruby, you may find it difficult to jump right into learning Rails. There are several good English-language resources dedicated to learning Ruby, for example:

Please note that some of the resources, while still great, still cover older versions of Ruby such as 1.6, and especially 1.8, and do not include some of the syntax you'll see in everyday Rails development.

What is Rails?

Rails is a web development framework written in the Ruby programming language. It is designed to make programming web applications easier by making a number of assumptions about what each developer needs to create a new project. It allows you to write less code in the programming process, in comparison with other languages ​​and frameworks. Professional Rails developers also note that it makes developing web applications more fun =)

Rails is headstrong software. It makes the assumption that there is a "better" way to do something, and it is designed in such a way that it encourages that way - and in some cases even discourages alternatives. If you learn "The Rails Way" you may discover a significant increase in your productivity. If you persist in bringing old habits from other languages ​​into Rails development, and try to use patterns learned elsewhere, you will have a less happy development experience.

The Rails philosophy includes two important guiding principles:

  • Don't Repeat Yourself: DRY is a software development principle that states that "Every piece of information should have a single, non-redundant, authoritative representation in the system." Don't write the same information over and over again, the code will be easier to maintain and will be more extensible and less buggy.
  • Convention Over Configuration: Rails has opinions about the best ways to do a lot of things in a web application, and defaults to those conventions rather than forcing you to tinker with numerous configuration files.

Creating a New Rails Project

The best way to use this guide is to go through it step by step. All steps are essential to running the example application, and no additional code or steps are required.

By following this tutorial, you will create a Rails project called blog, a very simple web blog. Before we start creating an application, we need to make sure that Rails itself is installed.

The following examples use $ to indicate a terminal input line on UNIX-like operating systems, although it may be configured differently. If you are using Windows, the line will look something like c:\source_code>

3.1. Installing Rails

Before installing Rails, you must ensure that the required pre-dependencies are installed on your system. These include Ruby and SQLite3.

Open command line applications. On macOS, open Terminal.app, on Windows, select "Run" from the Start menu and write "cmd.exe". Any commands starting with a dollar sign $ must be run on the command line. Make sure you have installed Current version Ruby:

$ ruby ​​-v ruby ​​2.5.0

Rails requires Ruby version 2.4.1 or later to be installed. If the version number is less than this, you will need to install a new copy of Ruby.

To quickly install Ruby and Ruby on Rails on a system, Windows users can use Rails Installer. Additional Methods installations for most operating systems can be seen at ruby-lang.org.

If you are working on Windows, you need to install the Ruby Installer Development Kit.

You will also need an SQLite3 database installation.

Many popular UNIX-like OSes ship with a reasonable version of SQLite3. On Windows, if you installed Rails using the Rails Installer, you already have SQLite installed. Other users may refer to the SQLite3 website for installation instructions. Check that it is installed correctly and is contained in your PATH:

$sqlite3 --version

The program must report its version.

To install Rails, use the gem install command provided by RubyGems:

$ gem install rails

To check that everything is installed correctly, you need to do the following:

$rails --version

If it says something like "Rails 5.1.1", you can continue.

3.2. Creating a Blog Application

Rails comes with a number of scripts, called generators, designed to make a developer's life easier by generating everything needed to get started on a specific task. One of them is the New Application Generator, which gives you the framework of a Rails application so you don't have to write it yourself.

To use this generator, open a terminal, go to a folder where you have permission to create files and write:

$rails new blog

This will create a Rails application named Blog in the blog directory and install the gems whose dependencies are mentioned in the Gemfile when using bundle install .

When using Windows Subsystem for Linux, there are some restrictions on messages file system, indicating that the spring and listen gems should be disabled, which can be done by running rails new blog --skip-spring --skip-listen .

You can see all the possible command line options that the Rails application builder accepts by running rails new -h .

Once you have created the blog application, go to its folder:

The blog directory contains several automatically generated files and folders that define the structure of a Rails application. Most of the work in this tutorial will take place in the app folder, but for now let's go over the functions of each folder that Rails creates in a new application by default:

File/Folder Purpose
app/ Contains controllers, models, views, helpers, mailers, channels, jobs and assets of your application. We'll look at this folder in more detail next.
bin/ Contains Rails scripts that start your application, and the directory can also contain other scripts that you use to configure, update, deploy, or run.
config/ Route configurations, your application database, etc. This is covered in more detail in Configuring Rails Applications
config.ru Rack configuration for the Rack-based servers used to run the application. For more information about Rack, visit the Rack website.
db/ Contains your current database schema as well as database migrations.
Gemfile
Gemfile.lock
These files allow you to specify which gem dependencies your Rails application needs. These files are used by the Bundler gem. For more information about Bundler, visit the Bundler website.
lib/ External modules for your application.
log/ Application log files.
package.json This file allows you to specify which npm dependencies are required for your Rails application. This file is used by Yarn. For more information about Yarn, visit the Yarn website.
public/ The only folder that is accessible from the outside as is. Contains static files and compiled assets.
Rakefile This file finds and loads tasks that can be run on the command line. A specific task is available in all Rails components. Instead of changing the Rakefile, you can add your own tasks by adding files to the application's lib/tasks directory.
README.md This is an introductory guide to your application. It should be edited to tell others what your application does, how to configure it, etc.
storage/ Active Storage files for the Disk service. This is covered in the Active Storage Overview guide.
test/ Unit tests, fixtures and other testing apparatus. This is covered in the Testing Rails Applications guide.
tmp/ Temporary files (such as cache and pid files)
vendor/ Place for third party code. In a typical Rails application, it includes external gems.
.gitignore This file tells git which files (explicitly or by design) it should ignore. For more information on ignoring files, see GitHub - Ignoring files.
.ruby-version This file contains the default version of Ruby.

Hello Rails!

First, let's display some text on the screen. For this you need running server of your Rails application.

4.1. Starting the web server

In fact you already have functional application on Rails. To be sure, you need to run a web server on your machine. This can be done by running next command from the blog directory:

$ bin/rails server

If you are using Windows, you should pass scripts from the bin folder directly to the Ruby interpreter, i.e. ruby ​​bin\rails server .

Compiling CoffeeScript and compressing JavaScript assets requires a JavaScript runtime on your system, and not having one will result in an execjs error during asset compilation. Typically, macOS and Windows come with a JavaScript runtime installed. Rails adds the mini_racer gem to the generated Gemfile of the new application in a commented line; you can uncomment it if necessary. therubyrhino is the recommended runtime for JRuby users and is added to the Gemfile if the application is generated under JRuby. You can learn all about the supported runtimes in ExecJS

This will launch Puma, a web server distributed with Rails by default. To see the application in action, open a browser window and go to http://localhost:3000. You should see the default information page Rails:

To stop the web server, press Ctrl+C in the terminal where it is running. To verify that the server has been stopped, you should see the command line cursor again. On most UNIX-like systems, including macOS, this will be the dollar sign $. In development mode, Rails generally does not require the server to be stopped; all changes you make to files are automatically picked up by the server.

The Welcome Aboard page is a kind of test for a new Rails application: it shows that your programs are configured correctly enough to display the page.

4.2. Say hi to Rails

For Rails to say "Hello", you need to create at least controller And view(performance).

The purpose of the controller is to receive specific requests to the application. Routing decides which controller will receive which requests. There is often more than one route to each controller, and different routes may be handled differently action. The purpose of each action is to collect information to provide it to the view.

The purpose of the view is to display this information in a human-readable format. An important distinction to note is that the place where information is collected is controller, not a view. The view should only display this information. By default, view templates are written in a language called eRuby (Embedded Ruby), which is converted by a Rails request loop before being sent to the user.

To create a new controller, you need to run the "controller" generator and tell it that you want a controller called "Welcome" with an action called "index", like this:

$ bin/rails generate controller Welcome index

Rails will create several files and a route.

Create app/controllers/welcome_controller.rb route get "welcome/index" invoke erb create app/views/welcome create app/views/welcome/index.html.erb invoke test_unit create test/controllers/welcome_controller_test.rb invoke helper create app/ helpers/welcome_helper.rb invoke test_unit invoke assets invoke coffee create app/assets/javascripts/welcome.coffee invoke scss create app/assets/stylesheets/welcome.scss

The most important of them are, of course, the controller, located in app/controllers/welcome_controller.rb, and the view, located in app/views/welcome/index.html.erb.

Open the file app/views/welcome/index.html.erb in a text editor. Remove all existing code in the file and replace it with the following line of code:

If you submit the form again, you will see something like the following:

"First Article!", "text"=>"This is my first article.") permitted: false>

Now this action displays the parameters for the article that came from the form. However, it is still useless. Yes, you see the parameters, but you don't actually do anything with them.

5.4. Creating an Article Model

Models in Rails use a singular name, and their corresponding table in the database uses a plural name. Rails provides a model generator that most Rails developers use to create new models. To create a new model, run this command in your terminal:

$ bin/rails generate model Article title:string text:text

With this command we tell Rails that we want an Article model with the attribute title string type and attribute text text type. These attributes will automatically be added to the articles table and bound to the Article model.

Rails will respond by creating a series of files. Now we are only interested in app/models/article.rb and db/migrate/20140120191729_create_articles.rb (your name may be slightly different). The latter is responsible for creating the database structure, so we will look at it next.

Active Record is smart enough to automatically associate column names with model attributes, which means that inside Rails models there is no need to declare attributes, Active Record will do it automatically.

5.5. Starting a migration

As you have already seen, bin/rails generate model created the file database migration in the db/migrate directory. Migrations is a Ruby class designed to make it easy to create and modify database tables. Rails uses rake commands to run migrations, and it is possible to undo a migration after it has been applied to your database. The migration file name includes a timestamp to ensure that they are executed in the order in which they were created.

If you look in the file db/migrate/YYYYMMDDHHMMSS_create_articles.rb (remember, your file has a slightly different name), this is what you will find there:

Class CreateArticles< ActiveRecord::Migration def change create_table:articles do |t| t.string:title t.text:text t.timestamps end end end

This migration creates a change method that is called when this migration runs. The actions defined in this migration are also reversible, which means that Rails knows how to undo the changes made by this migration in case you decide to undo them later. When you run this migration it will create an articles table with a string column and a text column. It will also create two timestamp fields to track when the article was created and updated.

Now we need to use the bin/rails command to start the migration:

$ bin/rails db:migrate

Rails will run this migration command and report that it has created the Articles table.

CreateArticles: migrating =============================================== === -- create_table(:articles) -> 0.0019s == CreateArticles: migrated (0.0020s) =========================== ==============

Since you are running in the development environment by default, this command will be applied to the database defined in the development section of your config/database.yml file. If you want to perform migrations in another environment, such as production, you must explicitly pass it when calling the command: bin/rails db:migrate RAILS_ENV=production .

5.6. Saving data in the controller

Back to the ArticlesController, we need to change the create action to use the new Article model to save data to the database. Open app/controllers/articles_controller.rb and change the create action to look like this:

Def create @article = Article.new(params[:article]) @article.save redirect_to @article end

Here's what happens here: Each Rails model can be initialized with the appropriate attributes, which will be automatically bound to the corresponding database columns. In the first line we do just that (remember that params[:article] contains the attributes we are interested in). @article.save is then responsible for saving the model to the database. Finally, we redirect the user to the show action, which we will define later.

You may be wondering why the A in Article.new is capitalized when all the other article links in this guide are capitalized. In this context, we are referring to a class called Article, which is defined in app/models/article.rb. Class names in Ruby must begin with a capital letter.

Now that there are validations, calling @article.save on an invalid article will return false . If you open app/controllers/articles_controller.rb again, you'll see that we're not checking the result of the @article.save call in the create action. If @article.save fails in this situation, we need to show the form to the user again. To do this, replace the new and create actions in app/controllers/articles_controller.rb with these:

Def new @article = Article.new end def create @article = Article.new(article_params) if @article.save redirect_to @article else render "new" end end private def article_params params.require(:article).permit(:title , :text) end

The new action now creates a new instance variable called @article , and you'll see why in a couple of paragraphs.

Note that in the create action we used render instead of redirect_to when save returns false. The render method is used to ensure that the @article object is passed back to the new template when it is rendered. This rendering is done within the same request as the form submission, while redirect_to tells the browser to make a different request.

5.11. Article Updates

We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating articles.

The first step is to add an edit action to the ArticlesController, typically between the new and create actions, as shown.

Def new @article = Article.new end def edit @article = Article.find(params[:id]) end def create @article = Article.new(article_params) if @article.save redirect_to @article else render "new" end end

The view will contain a form similar to the one we used when creating new articles. Create a file called app/views/articles/edit.html.erb and add the following to it:

Editing article

<%= form_with(model: @article, local: true) do |form| %> <% if @article.errors.any? %>

<%= pluralize(@article.errors.count, "error") %>

    <% @article.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %>

<%= form.label:title %>
<%= form.text_field:title %>

<%= form.label:text %>
<%= form.text_area:text %>

<%= form.submit %>

<% end %> <%= link_to "Back", articles_path %>

Right now we're pointing the form to an update action, which hasn't been defined yet, but we'll do that soon.

Passing the article object to the method will automatically set the URL for submitting the edited article form. This option tells Rails that we want this form to be submitted using PATCH , an HTTP method that is expected to be used for updates resources in accordance with the REST protocol.

Then you need to create an update action in app/controllers/articles_controller.rb . Add it between the create action and the private method:

Def create @article = Article.new(article_params) if @article.save redirect_to @article else render "new" end end def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render "edit" end end private def article_params params.require(:article).permit(:title, :text) end

The new method, update , is used when you want to update a record that already exists, and it takes a hash containing the attributes you want to update. As before, if there is an error updating the article, we want to show the form to the user again.

We reused the article_params method that we defined earlier for the create action.

It is not necessary to pass all attributes to update . For example, if @article.update(title: "A new title") was called, Rails will update only the title attribute, leaving all other attributes untouched.

<% @articles.each do |article| %> <% end %>
Title Text
<%= article.title %> <%= article.text %> <%= link_to "Show", article_path(article) %> <%= link_to "Edit", edit_article_path(article) %>

And we’ll also add app/views/articles/show.html.erb to the template so that the “Edit” link is also on the article page. Add the following at the end of the template:

... <%= link_to "Edit", edit_article_path(@article) %> | <%= link_to "Back", articles_path %>

And this is what our application looks like now:

5.12. Using partials to clean up repetition in views

Our edit page is very similar to the new page, in fact they use the same code to display the form. Let's remove this duplication by using a view partial. By convention, partial files begin with an underscore.

Create a new file app/views/articles/_form.html.erb with the following content:

<%= form_with model: @article, local: true do |form| %> <% if @article.errors.any? %>

<%= pluralize(@article.errors.count, "error") %>prohibited this article from being saved:

    <% @article.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %>

<%= form.label:title %>
<%= form.text_field:title %>

<%= form.label:text %>
<%= form.text_area:text %>

<%= form.submit %>

<% end %>

Let's now update the app/views/articles/new.html.erb view to use this new partial by rewriting it completely:

New article

<%= render "form" %> <%= link_to "Back", articles_path %>

And the same for the view app/views/articles/edit.html.erb:

Edit article

<%= render "form" %> <%= link_to "Back", articles_path %>

5.13. Deleting articles

Now we are ready to cover part "D" of CRUD, deleting from the database. Following the REST convention, the route to remove articles in the bin/rails routes output is as follows:

DELETE /articles/:id(.:format) articles#destroy

The delete routing method should be used for routes that destroy resources. If it were left as a normal get route, it would be possible to create the following malicious URLs:

look at this cat!

We use the delete method to destroy resources, and this route is associated with the destroy action in app/controllers/articles_controller.rb, which does not yet exist. The destroy method is usually the last CRUD action in a controller, and like other public CRUD actions, it must be placed before any private or protected methods. Let's add it:

Def destroy @article = Article.find(params[:id]) @article.destroy redirect_to articles_path end

The entire ArticlesController in the app/controllers/articles_controller.rb file should now look like this:

Class ArticlesController< ApplicationController def index @articles = Article.all end def show @article = Article.find(params[:id]) end def new @article = Article.new end def edit @article = Article.find(params[:id]) end def create @article = Article.new(article_params) if @article.save redirect_to @article else render "new" end end def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render "edit" end end def destroy @article = Article.find(params[:id]) @article.destroy redirect_to articles_path end private def article_params params.require(:article).permit(:title, :text) end end

You can call destroy on Active Record objects when you want to remove them from the database. Note that we don't need to add a view for this action since we are redirecting to the index action.

Listing Articles

<%= link_to "New article", new_article_path %> <% @articles.each do |article| %> <% end %>
Title Text
<%= article.title %> <%= article.text %> <%= link_to "Show", article_path(article) %> <%= link_to "Edit", edit_article_path(article) %> <%= link_to "Destroy", article_path(article), method: :delete, data: { confirm: "Are you sure?" } %>

Here we use link_to in a different way. We pass the named route as the second argument, and the options as another argument. The method: :delete and data: ( confirm: "Are you sure?" ) options are used as html5 attributes, so when a link is clicked, Rails will first show the user a confirmation dialog and then send the link using the delete method. This is done using JavaScript file rails-ujs , which is automatically included in the application layout (app/views/layouts/application.html.erb) when the application is generated. Without this file, the confirmation dialog will not be shown.

Congratulations, you can now create, view all and individually, update and delete articles.

Adding a second model

It's time to add a second model to the application. The second model will process comments on articles.

6.1. Generating the model

We intend to use the same generator that we used earlier when creating the Article model. This time we will create a Comment model containing a link to the article. Run the following command in a terminal:

$ bin/rails generate model Comment commenter:string body:text article:references

This command generates four files:

First let's take a look at app/models/comment.rb:

Class Comment< ApplicationRecord belongs_to:article end

This is very similar to the Article model we saw earlier. The difference is in the belongs_to:article line, which sets connection Active Record. You'll learn about connections in the next section of the guide.

The keyword (:references) used in the bash command is a special data type for models. It creates a new column in your database with the name of the represented model with _id appended, which can contain numeric values. To better understand, analyze the db/schema.rb file after performing the migration.

In addition to the model, Rails also made a migration to create the corresponding database table:

Class CreateComments< ActiveRecord::Migration def change create_table:comments do |t| t.string:commenter t.text:body t.references:article, foreign_key: true t.timestamps end end end

The t.references line creates numeric column named article_id , an index on it, and a foreign key constraint pointing to the id column of the articles table. Next, we start the migration:

$ bin/rails db:migrate

Rails is smart enough to only run migrations that haven't already been run on the current database, in our case you'll see:

CreateComments: migrating =============================================== == -- create_table(:comments) -> 0.0115s == CreateComments: migrated (0.0119s) ============================ ============

6.2. Connecting models

Active Record relationships allow you to easily declare relationships between two models. In the case of comments and articles, you could describe the relationship as follows:

  • Each comment belongs to one article.
  • One article can have many comments.

In fact, it's very close to the syntax that Rails uses to declare this connection. You've already seen the line of code in the Comment model (app/models/comment.rb) that makes each comment belong to an article:

Class Comment< ApplicationRecord belongs_to:article end

You need to edit app/models/article.rb to add the other side of the link:

Class Article< ApplicationRecord has_many:comments validates:title, presence: true, length: { minimum: 5 } [...] end

These two advertisements automatically make available a large number of opportunities. For example, if you have an @article instance variable containing an article, you can get all the comments belonging to that article in an array by calling @article.comments .

6.3. Adding a route for comments

As with the welcome controller, we need to add a route so that Rails knows which address we want to go to in order to see the comments. Open the config/routes.rb file again and edit it as follows:

Resources:articles do resources:comments end

This will create comments like nested resource in articles. This is the other side of capturing the hierarchical relationships that exist between articles and comments.

6.4. Generating a controller

Having the model, let's turn our attention to creating the appropriate controller. We will again use the same generator that we used before:

$ bin/rails generate controller Comments

Five files and an empty directory will be created:

Like any other blog, our readers will create their comments immediately after reading the article, and after adding a comment, they will be directed back to the article display page and see that their comment has already been reflected. In this regard, our CommentsController serves as a means of creating comments and removing spam, if any.

First we'll extend the Article show template (app/views/articles/show.html.erb) to allow a new comment to be added:

Title: <%= @article.title %>

Text: <%= @article.text %>

Add a comment:

<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>

<%= form.label:commenter %>
<%= form.text_field:commenter %>

<%= form.label:body %>
<%= form.text_area:body %>

<%= form.submit %>

<% end %> <%= link_to "Edit", edit_article_path(@article) %> | <%= link_to "Back", articles_path %>

This will add a form to the article display page that creates a new comment when the create action is called on the CommentsController . Here the form_with call uses an array, which will create a nested route such as /articles/1/comments .

Let's write create in app/controllers/comments_controller.rb:

Class CommentsController< ApplicationController def create @article = Article.find(params[:article_id]) @comment = @article.comments.create(comment_params) redirect_to article_path(@article) end private def comment_params params.require(:comment).permit(:commenter, :body) end end

It's a little more complicated than what you saw in the article controller. This is a side effect of the attachment you set up. Each request for a comment keeps track of the article the comment is attached to, so we first resolve the issue of retrieving the article by calling find on the Article model.

In addition, the code takes advantage of some of the methods available for connections. We use the create method on @article.comments to create and save a comment. This automatically links the comment so that it belongs to a specific article.

Once we've created a new comment, we take the user back to the original article using the article_path(@article) helper. As we've already seen, it calls the show action on the ArticlesController, which in turn renders the show.html.erb template. This is where we want to display comments, so let's add the following to app/views/articles/show.html.erb.

Title: <%= @article.title %>

Text: <%= @article.text %>

Comments

<% @article.comments.each do |comment| %>

Commenter: <%= comment.commenter %>

Comment: <%= comment.body %>

<% end %>

Add a comment:

<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>

<%= form.label:commenter %>
<%= form.text_field:commenter %>

<%= form.label:body %>
<%= form.text_area:body %>

<%= form.submit %>

<% end %> <%= link_to "Edit", edit_article_path(@article) %> | <%= link_to "Back", articles_path %>

Now you can add articles and comments to your blog and display them in the right places.

Refactoring

Now that we have working articles and comments, let's take a look at the app/views/articles/show.html.erb template. It became long and uncomfortable. Let's use partials to relieve it.

7.1. Rendering collections of partials

First, we'll make a comment partial showing all the comments for an article. Create a file app/views/comments/_comment.html.erb and put the following in it:

Commenter: <%= comment.commenter %>

Comment: <%= comment.body %>

Then you can change app/views/articles/show.html.erb like this:

Title: <%= @article.title %>

Text: <%= @article.text %>

Comments

<%= render @article.comments %>

Add a comment:

<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>

<%= form.label:commenter %>
<%= form.text_field:commenter %>

<%= form.label:body %>
<%= form.text_area:body %>

<%= form.submit %>

<% end %> <%= link_to "Edit", edit_article_path(@article) %> | <%= link_to "Back", articles_path %>

This will now render the app/views/comments/_comment.html.erb partial once for each comment in the @article.comments collection. Since the render method iterates through the @article.comments collection, it assigns each comment to a local variable named like the partial, in this case comment , which is available to us in the partial for display.

7.2. Rendering a form in a partial

Let's also move the new comment section to our partial. Again, create a file app/views/comments/_form.html.erb containing:

<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>

<%= form.label:commenter %>
<%= form.text_field:commenter %>

<%= form.label:body %>
<%= form.text_area:body %>

<%= form.submit %>

<% end %>

Then change app/views/articles/show.html.erb like this:

Title: <%= @article.title %>

Text: <%= @article.text %>

Comments

<%= render @article.comments %>

Add a comment:

<%= render "comments/form" %> <%= link_to "Edit", edit_article_path(@article) %> | <%= link_to "Back", articles_path %>

The second render just defines the partial template we want to render, comments/form . Rails is smart enough to put an underscore on this line and understand that you meant to render the _form.html.erb file in the app/views/comments directory.

The @article object is available in any partials rendered in the view, since we defined it as an instance variable.

Deleting comments

Another important feature of the blog is the ability to remove spam. To do this, you need to insert some link in the view and a destroy action in the CommentsController.

Commenter: <%= comment.commenter %>

Comment: <%= comment.body %>

<%= link_to "Destroy Comment", , method: :delete, data: { confirm: "Are you sure?" } %>

Pressing this new link"Destroy Comment" will run DELETE /articles/:article_id/comments/:id in our CommentsController, which will then be used to find the comment we want to delete, so let's add a destroy action to our controller (app/controllers/comments_controller.rb) :

Class CommentsController< ApplicationController def create @article = Article.find(params[:article_id]) @comment = @article.comments.create(comment_params) redirect_to article_path(@article) end def destroy @article = Article.find(params[:article_id]) @comment = @article.comments.find(params[:id]) @comment.destroy redirect_to article_path(@article) end private def comment_params params.require(:comment).permit(:commenter, :body) end end

The destroy action will find the article we're viewing, find the comment in the @article.comments collection, and then remove it from the database and return us back to viewing the article.

8.1. Deleting Related Objects

If you delete an article, the comments associated with it must also be deleted, otherwise they will simply take up space in the database. Rails allows you to use the dependent option on a link to achieve this. Modify the Article model, app/models/article.rb , as follows:

Class Article< ApplicationRecord has_many:comments, dependent: :destroy validates:title, presence: true, length: { minimum: 5 } [...] end

Safety

9.1. Basic authentication

If you publish your blog online, anyone can add, edit and delete articles or delete comments.

Rails provides a basic HTTP authentication system that works well in this situation.

In ArticlesController we need a way to block access to various actions if the user is not authenticated. Here we can use the Rails http_basic_authenticate_with method to allow access to the required actions, if the method allows it.

To use the authentication system, we'll define it at the top of our ArticlesController in app/controllers/articles_controller.rb. In our case, we want the user to be authenticated for every action except index and show , so we'll write it like this:

Class ArticlesController< ApplicationController http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show] def index @articles = Article.all end # пропущено для краткости

We also want to allow only authenticated users to delete comments, so in CommentsController (app/controllers/comments_controller.rb) we'll write:

Class CommentsController< ApplicationController http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy def create @article = Article.find(params[:article_id]) # ... end # пропущено для краткости

Now if you try to create new article, then you will encounter an HTTP Basic Authentication call:

Other authentication methods are also available for Rails applications. Two popular add-ons for Rails are Devise and Authlogic, among others.

9.2. Other thoughts on safety

Security, especially in web applications, is a broad and detailed area. The security of your Rails application is covered in more detail in the guide Security of Rails Applications The simplest way to work with Rails is to store all external data in UTF-8. If not, the Ruby and Rails libraries will often be able to convert your native data to UTF-8, but this doesn't always work reliably, so it's best to be sure that all external data is UTF-8.

If you make an error in this area, the most common symptom is a black diamond with a question mark inside appearing in the browser. Another common symptom is symbols such as "ü" appearing instead of "ü". Rails takes a number of internal steps to mitigate common cases of problems that can be automatically detected and corrected. However, if there is external data that is not stored in UTF-8, this can lead to these kinds of problems that Rails cannot automatically detect and fix.

The two most common data sources that are not in UTF-8 are:

  • Your Text Editor: Most text editors (such as TextMate) save files as UTF-8 by default. If your text editor doesn't do this, it can cause special characters entered into your patterns (such as é) to appear as a diamond with a question mark in the browser. This also applies to your i18N translation files. Most editors that do not default to UTF-8 (such as some Dreamweaver versions) offer a way to change the default to UTF-8. Do this.
  • Your database: Rails by default converts data from your database to UTF-8 on the edge. However, if your database does not use UTF-8 internally, it may not be able to store all the characters that your user will enter. For example, if your database uses Latin-1 internally, and your user enters Russian, Hebrew, or Japanese characters, the data will be lost as soon as it enters the database. If possible, use UTF-8 as internal storage in your database.

I've been wanting to learn Ruby on Rails at some basic level for a long time. Without specific purpose. Rather, just for yourself, to better understand what is so special about it (unlike 100,500 other technologies and frameworks), which allows you to quickly create and scale fairly loaded Internet projects. A secondary reason was the desire to try new approaches to learning. When I was studying to become a programmer, we only had books and forums where you could ask for advice. Now there are interactive textbooks and online programming schools, great amount screencasts (almost a dream: watching gurus program), knowledge bases like stackoverflow.com and tons of source code on GitHub, where you can spend hours studying the source code of real pros. I decided to set aside the next few nights (and there was simply no time during the day) to try new ways of learning in action.

Night one

Starting to learn Ruby on Rails without at least minimal knowledge of Ruby itself would be strange. I already took on the interactive guide ruby-lang.org. But as soon as I passed it, I immediately forgot everything. Its creators promise that it will take fifteen minutes to complete and master the syntax of Ruby. It took me thirty. True, with constant distraction on Twitter. The process looks something like this. They tell you: “Arrays in Ruby are declared like this, and data is retrieved from arrays like this. Now let's try to make an array and extract N elements from it. We'll check." You read how everything works and try it right away. Of course, you won’t learn Ruby this way. It’s better to think of it as a super-express course that works.

And yet Ruby itself is very far from the Ruby on Rails framework. I wanted to master the rails. From our article about online education, I definitely remembered the sensational Zombie for Rails course railsforzombies.org. It's the same as Try Ruby, an interactive tutorial that teaches you how to build rail applications right off the bat. First, they give you a mini-lecture (in English, but everything is very clear - turn on subtitles) about the file structure of a rail application, the CRUD approach to working with data, they explain how to implement MVC model in rails, and so on. After each video, you are asked to complete tasks to consolidate the material. Everything seems simple and clear, the course flies by unnoticed in an hour or two (it is short). But! After the course, did I feel like I could write a rail application? Unfortunately no!

Night two

One of the reasons why some people appear after Rails for Zombies basic knowledge, but there is no certainty - this virtual environment where the training takes place. On the one hand, it reduces the entry threshold to the limit: you don’t have to worry about your surroundings. On the other hand, you don’t create anything real along the way - no “Hello World” for you at the exit. And most importantly, from which side to approach its creation is unclear. From that moment on, I wanted to try Ruby on Rails in action, actually installing it on the system (before that I didn’t even have to try), and create a simple application from scratch.

I don’t remember how, but quite by accident I came across a very successful screencast course in Russian rails.hasbrains.org. Thanks to the author for his competent presentation: he methodically explains the principles of operation of the rail application in detail, immersing you in all the necessary subtleties along the way. Long story short, I spent the entire second night of the experiment watching the first half of over thirty episodes of these screencasts.

The picture of how an application is generated, how to work with the rail console, how to create models and migrations, how to update models and how to validate data in them, RESTful controllers, and so on has finally been fixed in my head. Watching each of the episodes, I immediately tried everything in action, building a fully working rail application. It became clear how the rails are designed in principle.

Night three

On the third night, the last episodes of the screencasts remained, which I managed to watch in one sitting: working with rails no longer seemed so wild. At that moment, someone told me that the Rails for Zombies course had a sensible and much deeper continuation. True, the course is already paid and hosted within the school Programming Code School www.codeschool.com. It wasn't a shame to pay 25 bucks to get access to all the school's courses. This is a monthly price, so if you don't like it, don't forget to cancel your subscription.

The Rails for Zombies 2 course turned out to be very successful indeed. True, a lot of it was a repetition of what I saw in the screencasts, but it was even partly pleasant. Five levels and five blocks of exercises that you do directly in the interactive console. By this point, the rails already seemed logical, understandable and usable.

In Code School you can program directly in the browser while completing course assignments

What's next?

Have I learned how to do complex projects? No. But I definitely realized the approaches used in the rails and understood their convenience. I learned how to quickly create simple applications and increase its functionality in a super short time using gems written by the community. I caught the courage and continue to enjoy learning the best practices using Code School programs (I’m currently taking a course on unit tests). And it makes me damn happy that learning technology has become so easy.

What is Ruby on rails and why is it so popular?

Rails this is a web framework, in turn, a framework is a set of applications and various tools for creating a web application.
A framework is the framework of a web application, with huge selection settings and with the goal of making development as convenient and enjoyable for the developer as possible.

You are like a creator, create whatever you want. After all, the main thing in development is to set goals and achieve them, while knowing that the path you take to achieve is the best!
So, what is rails and what makes it so great?

7 pillars of ruby ​​on rails excellence

First, Ruby On Rails is Ruby
Ruby on Rails is a framework written in best language Ruby programming.
The beauty and convenience of programming simply cannot be described in words. Ruby on Rails complements this perfect language with new methods and classes for the interaction of objects and classes.

All aspects of interaction between the framework system are very thoughtful and structured.
Ruby on Rails has a lot of things that other frameworks don’t have, Ruby on Rails is developing by leaps and bounds, and other web frameworks are barely keeping pace.

Second, Ruby on Rails uses MVC

MVC is an architectural template (pattern) that provides for the division of application code into three parts: Model (model), View (view) and Controller (controller).

Model contains the mathematical logic of the application, associative connections between models, various callbacks and the main application code are indicated here.
Representation are used to display information to the user, a view is, GUI application or web interface of a web application. Here are various html forms, css styles and javascript.
Controller deals with binding the model to the view and processing the application user request. Here you use routes to configure the routing of your application.
Using MVC allows you to write cleaner and more structured code, which significantly speeds up development while making the application easier to maintain.

Third, Ruby on Rails uses CoC
CoC - Convention over Configuration - the whole idea is that by default the framework is already perfectly configured. Ruby on Rails comes with a set of extremely convenient conventions that allow you to start developing your application immediately after installing Ruby on Rails and creating a new project. If necessary, you can change the default settings (they are called an agreement) and use your own, but this, as a rule, is not only unnecessary, but also often harmful.

The fourth whale, DRY
DRY - Don’t Repeat Yourself (Don’t repeat yourself!) is another development principle underlying the Ruby on Rails web framework and the ruby ​​language itself. This principle instructs the developer to identify repeated fragments in the code and move them into separate methods, classes or modules, depending on the situation. In Ruby on Rails, this principle appears in many places, allowing you to write less code, less testing, and easier to maintain developed code. For example, in a view, various partials are available for use - these are patterns for repeating code that are simply called in the code, for example for Forms. This not only improves the readability of the code, but also adds flexibility to change or add new information.

The fifth pillar is CRUD

CRUD - create, read, update, delete - “creation, read, update, delete”) is a methodology used to create controllers. Using a standard with which you can clearly define controller actions for complete manipulation of any object. You can also add your own actions without any problems.
Also, rails uses not only POST and GET request, and such as PUT and DELETE. Giving you more control over data

The sixth pillar of ORM

ORM (object-relational mapping) is a programming technology that helps to work with a database in a programming language without using different sql languages to manipulate the database. It uses object-oriented programming in ruby.
The whole idea is that a table is a class, its rows are objects, its columns are properties of objects.
Class methods perform operations on tables.
Object methods perform operations on individual strings.

The seventh whale of haml sass/less
The idea is to use simplified and more functional languages ​​such as haml and sass/less. Which increase the readability of the code, making development more convenient and are automatically interpreted into their parents html and css.

And there are also many more advantages, for example, installing various additional libraries (gems) in one command. Excellent free Heroku, which allows you to monitor the performance of your local application in production on a remote cloud. Various ready-made solutions from the Ruby on Rails documentation. And the ability to generate code for faster deployment of a web application.

The goal was to present the main features of the Ruby on Rails framework. I hope you are interested, and another cool rubyist will soon appear in the web world!

In this article I want to tell you how to create a simple application that works with a MySQL database in the Ruby on Rails 3 environment. You can think of this material as step by step guide for beginner Rails programmers.

So, for work we need installed rails and rubygems. Yesterday I had a problem with the latter, so I had to remove the rubygems1.8 package (it’s not clear how it ended up in the system) and install rubygems1.9 Let me remind you that I am developing on Ubuntu, although for Windows I think the Rails console commands will be the same. As a development environment I use NetBeans with a plugin for Ruby on Rails. My colleague wrote well about the installation.

Checking links

You need to make sure that the /usr/bin directory contains rails, rake, ruby, bundler symlinks to files from the /usr/local/ruby/bin directory. To view links use the command:

depending on what you want to filter.

Creating an application

I created a special directory for my ruby ​​applications.

mkdir /home/andrey/ruby
cd /home.andrey/ruby

Rails has many console utilities that make your work much easier, especially for prototyping. To create an application that uses mysql databases let's run the command:

app is the name of our new application. After executing the command, we will see how rails made us the framework of the future application.

root@vaio:~/ruby# rails new app -d mysql
create
create README
create Rakefile
create config.ru
create.gitignore
create Gemfile
create app
create app/controllers/application_controller.rb
create app/helpers/application_helper.rb
create app/mailers
create app/models
create app/views/layouts/application.html.erb
create config
create config/routes.rb
create config/application.rb
create config/environment.rb
create config/environments
create config/environments/development.rb
create config/environments/production.rb
create config/environments/test.rb
create config/initializers
create config/initializers/backtrace_silencers.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/secret_token.rb
create config/initializers/session_store.rb
create config/locales
create config/locales/en.yml
create config/boot.rb
create config/database.yml
create db
create db/seeds.rb
create doc
create doc/README_FOR_APP
create lib
create lib/tasks
create lib/tasks/.gitkeep
create log
create log/server.log
create log/production.log
create log/development.log
create log/test.log
create public
create public/404.html
create public/422.html
create public/500.html
create public/favicon.ico
create public/index.html
create public/robots.txt
create public/images
create public/images/rails.png
create public/stylesheets
create public/stylesheets/.gitkeep
create public/javascripts
create public/javascripts/application.js
create public/javascripts/controls.js
create public/javascripts/dragdrop.js
create public/javascripts/effects.js
create public/javascripts/prototype.js
create public/javascripts/rails.js
create script
create script/rails
create test
create test/fixtures
create test/functional
create test/integration
create test/performance/browsing_test.rb
create test/test_helper.rb
create test/unit
create tmp
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create vendor/plugins
create vendor/plugins/.gitkeep

We go to the folder with it and install the necessary gems. Gems are plug-in libraries required for the project (analogous to PHP’s PECL and PEAR).

After this, the console will show something like this:

andrey@vaio:~/ruby/app> sudo bundle install
Using rake (0.8.7)
Using abstract (1.0.0)
Using activesupport (3.0.0)
Using builder (2.1.2)
Using i18n (0.4.2)
Using activemodel (3.0.0)
Using erubis (2.6.6)
Using rack (1.2.1)
Using rack-mount (0.6.13)
Using rack-test (0.5.6)
Using tzinfo (0.3.23)
Using actionpack (3.0.0)
Using mime-types (1.16)
Using polyglot (0.3.1)
Using treetop (1.4.8)
Using mail (2.2.9)
Using actionmailer (3.0.0)
Using arel (1.0.1)
Using activerecord (3.0.0)
Using activeresource (3.0.0)
Using bundler (1.0.3)
Using mysql2 (0.2.6)
Using thor (0.14.4)
Using railties (3.0.0)
Using rails (3.0.0)
Your bundle is complete! Use `bundle show ` to see where a bundled gem is installed.

This means that all gems are installed and connected. If something is missing, then bundle itself will download them from rubygems and install them. This is what I was missing in PHP for a long time; in essence, it turns out to be a project installer. The list of dependent gems is located in the Gemfile in the project root.

Configuration

Now we need to specify the access details to the database of our project. Open the project in NetBeans: New Project -> Ruby -> Ruby on Rails application with existing source. We indicate the path, in my case it will be (/home/andrey/ruby/app) and the name of the project (app). For the Ruby Platform, we select the one installed on the system, rather than the one built into NetBeans. Click Finish and the project is created. Open the Configuration pseudo-folder and the database.yml file. Here you need to specify a login and password to access the database, preferably for all three environments at once (development, test, production). Environment is the environment in which our application will run,

  • development - developer's computer,
  • production - industrial operation server,
  • test — work in testing mode on the continuous integration server or tester’s computer.

rails generate model User name:string hashed_password:string salt:string

You can immediately see what Rails has generated for us:

invoke active_record
create db/migrate/20101107054200_create_users.rb
create app/models/user.rb
invoke test_unit
create test/unit/user_test.rb
create test/fixtures/users.yml

Great, now we need to create a database. To do this we do:

andrey@vaio:~/ruby/app$ rake db:create
(in /home/andrey/ruby/app)
andrey@vaio:~/ruby/app$ rake db:migrate
(in /home/andrey/ruby/app)
== CreateUsers: migrating ============================================= =======
— create_table(:users)
-> 0.0061s
== CreateUsers: migrated (0.0063s) ======================================================= ==

The console displays the added data. We look in phpmyadmin and see the new app_development and app_test databases, as well as the tables in them. Now it's time to add real data. To do this, launch the rails console

A console is not just a console, but an IRB console in the context of your application. As an example, let's create two users:

andrey@vaio:~/ruby/app$ rails console
Loading development environment (Rails 3.0.0)
irb(main):001:0> user1 = User.new
=> #
irb(main):002:0> user1.name = "andrey"
=> "andrey"
irb(main):003:0> user1.save
=> true
irb(main):004:0> user2 = User.new
=> #
irb(main):005:0> user2.name = “vasiliy”
=> "vasiliy"
irb(main):006:0> user2.save
=> true

irb(main):007:0> exit
andrey@vaio:~/ruby/app$

Let's look at the database, and indeed we have two users. I would like to note that Rails itself added primary key columns and created_at (creation date) and updated_at (modified date) fields to the model.

We have a model, and we have data too. It's time to launch our application.

andrey@vaio:~/ruby/app$ rails server
=> Booting WEBrick
=> Rails 3.0.0 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
INFO WEBrick 1.3.1
INFO ruby ​​1.9.2 (2010-08-18)
INFO WEBrick::HTTPServer#start: pid=4193 port=3000

The application is running, open the browser at the address and see the test page.

Great, the application is working. But it shows a regular HTML page from the /public/index.html folder. And we want dynamic. Open the second console window (since in the first we have the Ruby server running - WebRick), go to the folder with the project and type the following command there:

andrey@vaio:~/ruby/app$ rails generate controller index index
create app/controllers/index_controller.rb
route get "index/index"
invoke erb
create app/views/index
create app/views/index/index.html.erb
invoke test_unit
create test/functional/index_controller_test.rb
invoke helper
create app/helpers/index_helper.rb
invoke test_unit
create test/unit/helpers/index_helper_test.rb
andrey@vaio:~/ruby/app$

With this we created an Index controller, in it there is an Index action and the type of this action is index.html.erb We do Refresh (F5) in NetBeans and look at our files. Amazing. Now we need to somehow redirect the route for the main page to the controller action we created. Open the routes file (Configuration/routes.rb) and uncomment the following line there:

# You can have the root of your site routed with “root”
# just remember to delete public/index.html.
root:to => "welcome#index"

Only instead of welcome we also write index. Well, I’m used to the Zend Framework that the controller and action are called index by default. Don’t forget to delete (or rename) the public/index.html file).

root:to => "index#index"

We refresh the page in the browser and see that our view is now displayed.

Index#index

Great. Now we can code. Go to our newly created controller (Controllers -> index_controller.rb) and write the following action text there:

class IndexController< ApplicationController
def index
@users = User.find(:all)
end
end

Now open the view Views/index/index.html.erb and write the following code there:

Index#index


Find me in app/views/index/index.html.erb


<% for user in @users -%>
<%=user.name%>

<% end %>

By doing this, we tell Rails to iterate through the array of users and display their names. We refresh the page and see the list of users below.

Index#index

Find me in app/views/index/index.html.erb

andrey
vasiliy

Great! The application has been created!

Thank you!

If this article helped you, or you want to support my research and blog, here you go The best way do it:






2024 gtavrl.ru.