17. ACTIVE RECORD
articles
id title body
1 hello world This is a body
# app/models/article.rb
class Article < ActiveRecord::Base
end
article = Article.first
article.title
#=> "hello world"
18. ACTIVE RECORD
articles
id title body published
1 hello world This is a body 1
2 other art. Not published 0
articles = Article.where(published: 1)
articles.count
#=> 1
21. ACTIVE RECORD
articles
id title body author_id
# app/models/article.rb
1 ... ... 1 class Article < ActiveRec...
belongs_to :author
end
# app/models/author.rb
class Author < ActiveRec...
authors has_many :articles
id name end
1 John Doe
article = Article.first
article.author.name
#=> “John Doe”
23. ROUTING
# app/controller/hello_controller.rb
class HelloController < ApplicationController
def index
@name = params[:name]
end
end
http://example.com/hello/John
# config/routes.rb
get "hello/:name" => "hello#index"
action du contrôleur
URL
contrôleur
verbe HTTP
paramètre
25. HELPERS
# app/controller/articles_controller.rb
class ArticlesController < ApplicationController
def new
@article = Article.new
end
end
Title <%= form_for @article do |f| %>
<p><%= f.label :title, "Title" %><br />
<%= f.text_field :title %></p>
Body <p><%= f.label :body, "Body" %><br />
<%= f.text_area :body %></p>
<p><%= f.submit %></p>
<% end %>
Create Article
26. RAILTIES
$ rake routes
GET /hello/:name { :controller => "hello", :action => "index" }
$ rails server
Lance un serveur web sur http://localhost:3000/
$ rails console
Lance une console avec le contexte de l’application
>> Article.first.title
#=> "hello world"
27. GÉNÉRATEURS
$ rails generate model author name:string
invoke active_record
create db/migrate/20120108151543_create_authors.rb
create app/models/author.rb
instructions de création de la table authors
modèle Author