Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

Ruby on Rails - Generating resources

Ruby, Ruby on Rails, user, web, генерирование

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.

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking

Comments

Only authorized users can post comments.
Please, Log in or Sign up
МБ
April 21, 2019, 9:40 a.m.
Моисей Бушуев

Qt - Test 001. Signals and slots

  • Result:0points,
  • Rating points-10
AA
April 17, 2019, 7:40 p.m.
Anton Ablin

Qt - Test 001. Signals and slots

  • Result:73points,
  • Rating points1
E
April 17, 2019, 6:16 p.m.
Evgeny

Qt - Test 001. Signals and slots

  • Result:100points,
  • Rating points10
Last comments
April 21, 2019, 4:22 p.m.
Евгений Легоцкой

Через метод setIcon table.horizontalHeaderItem(0).setIcon("qrc://path/to/icon.png")
April 21, 2019, 3:48 p.m.
Евгений Легоцкой

Добрый день! Спасибо за комментарий. Там действительно лучше будет сделать с инициализацией по умолчанию.
U
April 18, 2019, 3:37 p.m.
Unreal_man

А как иконку в хедер задать?
u
April 18, 2019, 2:15 a.m.
uaa

доброго времени,большое спасибо за пример для начинающего)при адаптации к своему проекту столкнулся с таким ньансом:в vepolyline.h в 47 строке нужна инициализация по умолчанию: int m_pointF...
E
April 11, 2019, 12:49 p.m.
Evgeny

Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл Q_OBJECT в начале класса указать.
Now discuss on the forum
April 21, 2019, 4:16 p.m.
Евгений Легоцкой

Приветствую Нужно сохранять где-то выбранное значение, а потом восстанавливать его. Или использовать QSettings или добавить метод open(), в который передавать начальные значения для того...
R
April 19, 2019, 9:55 a.m.
RED_Spider

мені важко це зараз навіть перевірити, тому що знайшов коміт, це ще було в 2016 році, і цей код не буде працювати коректно зараз, єдине скажу що це були QThread
i
April 17, 2019, 3:03 p.m.
ilya.guzikov

BlinCT, на стороне ++ это делать необходимо так как в qml при использовании функции append происходит перерисовка всех точек лини(как я понимаю) и из-за этого при использовании больших массиво...
April 10, 2019, 11:20 a.m.
Алексей Внуков

может тоже кому надо будет - QML не принимает QVector<QVector<int>> , при попытке вывести полученый вектор QML показывает что это QVariant(QVector<QVector<int> ...
Join us in social networks

For registered users on the site there is a minimum amount of advertising