What for.
In this small article, which I would have read with pleasure myself a week ago, I tried to collect all the things that a person would need, if he wanted to write an application “from scratch” on RoR. That is, without delving into any of the areas, describe the necessary minimum of actions to install, configure and write your first application. Here it is collected, it seems to me, everything that is needed and I hope this text will save someone a few hours searching on the Internet ). I myself study RoR for the second week, so do not judge strictly).
Installation
Simply and quickly ror is put through rvm with
rvm.io.>\curl -L https://get.rvm.io | bash -s stable --rails --autolibs=enabled
')
Run rvm:
>source /___*/.rvm/scripts/rvm
* $ HOME in the future.
After that, a line should appear in $ HOME / .bash_profile:
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
and each time the rvm console opens, it will load, but this did not happen for me - I had to register in $ HOME / bashrc:
. ~/.bash_profile
Now everything must be fine.
We install the necessary (most likely it will be the latest) version of hack (how many are there and what is the difference you can see here -http: //www.ruby-lang.org).
>rvm install 1.9.3
Check for successful creation
>ruby -v
should return more details like
ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-linux].
During the installation, I accidentally installed several versions, which then caused some trouble). You can view a list of installed Ruby versions like this:
> rvm list
If there are several versions, the current one will be marked with "=>", the default one - "*", and the current and default one - "= *". You can change it for the version you want to use:
>rvm use ruby-1.9.2-p320 ( )
To change the default version of Ruby, write:
>rvm use ruby-1.9.2-p320 --default
Creating a project.
Now you can go directly to the creation of the project. Create a folder $ HOME / ROR / tickets, go into it and do the following.
>sudo gem install bundler >rails new tickets
When creating a project, all the necessary directories will be generated (app, config, db, log, etc.) and configuration files in the specified folder. For a small test project, we will need, in my case, a PostgreSQL database, a couple of gems (libraries) and a server running rails).
To start the server, you need to be running the command in the root of the folder with the created project:
>rails s -p 3000
where s is the server start command (server), and -p 3000 is the port number (port) by which the project will be available. To start the console, you need to type:
>rails c
where c is short for console
A list of all commands can be viewed by typing
> rails --h. Now at the address
localhost : 3000 we will see the project start page. You can also run any number of servers of other projects on other, non-occupied ports. In the course of work. at one moment, for some unknown reason, I had a problem starting the server - an error was issued that the server was already running - to solve it, you just need to delete the $ HOME / ROR / tickets / config / tmp / pids / server.pid file and start the server again.
Database.
To work with postgres, we add at the end of the Gemfile file, which should be located in the project root, the line
> gem 'pg'
save the file and do
>bundle install
we do it every time we make changes to the Gemfile, and then we also restart the server. To no longer come back, we immediately add
> gem 'haml-rails' for quick and convenient (after you get used to it)) markup of presentation templates. Now edit the attributes of the connection to the postgres in the database.yml file. It is located in the $ HOME / ROR / tickets / config / folder and should contain such a block:
development: host: localhost adapter: postgresql encoding: unicode database: tickets pool: 5 username: tickets
with the desired user and database name, I have these tickets and tickets, respectively).
It seems that all the preparations are completed and you can start creating a model, controller and presentation.
Model.
Create a model:
>rails g model user
where g is short for generate
The name of the model is written in the singular - the table in the database will be in the plural. This command will create model and migration files in $ HOME / ROR / tickets / app / models / user.rb and $ HOME / ROR / tickets / app / db / migrate / 20130425081208_create_users.rb. all files of controllers and models have the extension .rb, views - .html.haml (in our case of using haml). Through the migration, we will manage the work with the tables in the database via the console, which is very convenient (again, when you get used to it), they also provide ease of transferring the application to another server, for example. Add the required fields:
class CreateUsers < ActiveRecord::Migration def up create_table :users do |t| t.string :name, null: false t.boolean :role, null: false, default: false t.datetime :reg_date t.timestamps end end def down drop_table :users end end
We create two methods — up and down, which are used by default with functions for working with migrations — they, respectively, create and delete our table. The names of the data types will depend on the database used. The primary key is created by default and will be called id, but it can also be set explicitly:
create_table :users, :primary_key => :users_id do |t|
And if we don’t want to create a primary key at all, we write this:
create_table :users, :id => false do |t|
We save and write in the console:
>rake db:migrate
As a result of this command, all the failed methods are executed up from the migration files in the $ HOME / ROR / tickets / app / db / migrate / directory. All information about the state of the tables can be found in the $ HOME / ROR / tickets / app / db / shema.rb file.
>rake db:rollback
Runs the down method of the last migration, causing the table to be removed from the database. To roll back more migrations, add the STEP parameter to the rollback command:
>rake db:rollback STEP=3
This command will roll back the last three migrations. View the status of all migrations in the console:
>rake db:migrate:status
If you need to run a particular method from a specific migration, then add the VERSION parameter:
>rake db:migrate:up VERSION=000001
In the model file ($ HOME / ROR / tickets / app / models / user.rb) we only need to do one thing now - define the table fields that will be available for change from the controller, for security reasons, as I understand it). To do this, we write the following:
class User < ActiveRecord::Base attr_accessible :name, :role end
By the way, the haml syntax is very sensitive to tabs - they can be very well tracked in the editor that I use - Sublime Text.
While the application is not working, in order to make sure that all the created tables are really created and function as they should be, you can use the console:
>user = User.new(name:"Test",role:"true")
this command will not write to the table, but will create a ruyi object in memory with all the attributes set. And now make a record:
>user.save
If successful, should return true. You can create a record with one - create command:
>User.create(name:"Test",role:"true")
To check if there is an object in the database, you can use find:
>User.find(1)
returns an object or error: "ActiveRecord :: RecordNotFound: Couldn't find User with id = 1", as well as the generated sql query to the database.
You can search for specific fields:
>User.find_by_name("Test")
A few more convenient methods that will probably come in handy at first:
> User.first and User.last return the first and last entries in the table, respectively, and User.all returns an array of all the objects in the table.
Controller.
Create a controller:
>rails g controller users
As a result of this command, a controller file will be created: $ HOME / ROR / tickets / app / controllers / users_controller.rb and a directory for views:
$ HOME / ROR / tickets / app / views / users /. Each method of the controller will correspond to a view with the same name in this folder. They can be created manually, or you can immediately after creating the controller:
>rails g controller users index,list
In this case, view files will be created automatically in the $ HOME / ROR / tickets / app / views / users / folder and will be called (if you did not forget to connect haml) index.html.haml and list.html.haml. You can delete the controller as follows:
>rails d controller users
where d is short for destroy
Defining the index method, which is created by default, is not necessary. The content of our users controller will be as follows:
class UsersController < ApplicationController def list @users_list=User.all end end
In the users_list, there will be an array of user objects, which we in theory have already added from the console, and "@" means that the variable will be transferred to the template.
Representation.
Now create a view, I just created this file with my hands in the correct directory:
$ HOME / ROR / tickets / app / views / users / list.html.haml
You can read the HAML documentation here (http://haml.info/tutorial.html), but for now you will need a minimum of knowledge about it, for example, that instead of the opening and closing tags it uses "% tag". That is, after rendering a template containing% html, we will get a page with
<html></html>
. The nesting level is specified by tabulation, tag attributes are written “hash-like” in curly brackets:
%td{colspan=>"2"}
will turn into
<td colspan="2"></td>
and the content is separated by a space:% td test. Thus, the contents of our view:
%table{:border=>"1"} %tr %td %td - @users_list.each do |users| %tr %td= users.name %td %input{:type=>"checkbox",:name=>"role_#{users.id}",:checked=>users.role} %br
The hyphen is the executable code in the template. Here we walk through an array of objects and loop out its methods — the name and role fields and id fields.
All views are wrapped into the main template, which is located in $ HOME / ROR / tickets / app / views / layouts / application.html.haml
Remove everything in it and make it as simple as possible:
!!! %html{:lang => "en"} %head %title Test %body =yield
The contents of all our generated templates are substituted for = yield. The main thing is not to be mistaken with the levels of nesting, at first it really strained me).
Routes.
And there was only one small step left - editing the route config file (url) - routes.rb. It is located at $ HOME / ROR / tickets / config /. It describes all the routes of our project. Now there will only be two entries:
Tickets::Application.routes.draw do root :to => "users#index"
This is the root path to the “main” page (the contents of the /users/index.html.haml template will be displayed, even though the index method is not defined in the controller) and the path to the user list output page. If the method will post a request, it will have to be written like this:
post "users / add".
Now everything should work)