Evgenii Legotckoi
Evgenii LegotckoiMay 15, 2016, 4:30 a.m.

Ruby on Rails - Generating resources

Once managed to get in a previous article , a working version of the web application in Ruby, I went on to deal with the development and generation of resources, as well as with the study of architecture, Ruby on Rails web application. Fortunately this framework uses the MVC pattern, which is also used to Qt, so the overall understanding of architecture problems should arise.

During the search of sources of information in the style of "Ruby for Dummies", "Ruby in 21 days", etc. I came, apparently, a very great resource which is a translation of the book Ruby on Rails Tutorial by Michael Hartl. The first impression of the book was positive. So that further self-study, perhaps, will be spending on this resource.

From the first pros who have found it so references to the development environment RubyMine from JetBrains. I'm already familiar with products such as WebStorm, PHPStorm, Intellij IDEA and based on it AndroidStudio, so at this point chose this environment. What's strange Google for Ruby IDE requests and similarly, showed no information on this development environment, probably have not untwisted.


Resource generation USER

In the above named book offers after the creation of the first test application to add to the database table with the user accounts, and project our newfound test blog all necessary to work with the user files, ie the page to add, delete, view the list of users.

That is, the following files:

  • db/migrate/20130305221714_create_users.rb
  • app/models/user.rb
  • test/models/user_test.rb
  • test/fixtures/users.yml
  • app/controllers/users_controller.rb
  • app/views/users
  • app/views/users/index.html.erb
  • app/views/users/edit.html.erb
  • app/views/users/show.html.erb
  • app/views/users/new.html.erb
  • app/views/users/_form.html.erb
  • test/controllers/users_controller_test.rb
  • app/helpers/users_helper.rb
  • test/helpers/users_helper_test.rb
  • app/views/users
  • app/views/users/index.json.jbuilder
  • app/views/users/show.json.jbuilder
  • app/assets/javascripts/users.js.coffee
  • app/assets/stylesheets/users.css.scss
  • app/assets/stylesheets/scaffolds.css.scss

And all of these files are generated automatically by the scaffold command, which generates all the necessary code. Thus, it is necessary to add to the database table with the following form:

  • id - a unique string identifier, data type integer;
  • name - user name, data type string;
  • email - postal address, the data type string.

To do this, go to the blog directory automatically generated content in a previous article (mine is C:\Sites\blog) and execute the following command:

$ rails generate scaffold User name:string email:string

As you can see, there does not appear id records, as it is automatically generated. Setting User - is responsible for the name of the table, and as a result generated a table called users. Also as a result of this program code is added to a couple of fields in a table. You can verify this by looking in the SQLite database, but it can be done with the help of SQLiteStudio program, by the way recommend as a very handy tool. These additional fields will be the date of creation and update date.

But to see the data in the database so you can not initially. Because the template has been created, but the table has not been added to the database. For this purpose it is necessary to upgrade, that is to migrate the following additions to the database command:

$ bundle exec rake db:migrate

I confess, I have it just did not work out, because I forgot to install the bundle. Correcting this situation the team:

$ gem install bundler

Well, after the migration, run the server:

$ rails server

And we try to work with users. To do this, go to the following address in your browser:

URL Действие Назначение
/users
index
страница, для отображения списка всех пользователей
/users/1
show
страница показывающая пользователя с id
1
/users/new
new
страница для создания нового пользователя
/users/1/edit
edit
страница для редактирования пользователя с id
1

But I have not taken off the case, instead of showing the expected page, an error page.

The matter turned out that the code generate is in conflict with the code in application.html.erb file that serves as a template for posting information about our users. After some searching on the net, managed to solve the problem of changing the application parameter to default

It was:

<!DOCTYPE html>
<html>
<head>
  <title>Blog</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

It became:

<!DOCTYPE html>
<html>
<head>
  <title>Blog</title>
  <%= stylesheet_link_tag    'default', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'default', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

Result

As a result, it managed to get the desired page on adding users, their editing, and deleting.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 7:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 5:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 6:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 8:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 5:57 a.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 1:18 a.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 3:48 a.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks