7. www.tinci.fr
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"
8. www.tinci.fr
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
10. www.tinci.fr
Active Record
articles
id title body author_id
1 ... ... 1
authors
id name
1 John Doe
# app/models/article.rb
class Article < ActiveRec...
belongs_to :author
end
!
# app/models/author.rb
class Author < ActiveRec...
has_many :articles
end
!
article = Article.first
!
article.author.name
#=> “John Doe”
14. www.tinci.fr
Helpers
# app/views/articles/index.html.erb
<%= @articles.each do |article| %>
<p><%= link_to article.title, article %></p>
<% end %>
# app/controller/articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
end
<p><a href="/articles/1">hello world</a></p>
15. www.tinci.fr
Helpers
# app/controller/articles_controller.rb
class ArticlesController < ApplicationController
def new
@article = Article.new
end
end
<%= form_for @article do |f| %>
<p><%= f.label :title, "Title" %><br />
<%= f.text_field :title %></p>
!
<p><%= f.label :body, "Body" %><br />
<%= f.text_area :body %></p>
!
<p><%= f.submit %></p>
<% end %>
Title
Body
Create Article
16. www.tinci.fr
Railties
$ rake routes
GET /hello/:name { :controller => "hello", :action => "index" }
$ rails server
Starts a web server listening on http://localhost:3000/
$ rails console
Starts an interactive console in the application context
>> Article.first.title!
#=> "hello world"
17. www.tinci.fr
Generators
$ rails generate model author name:string
invoke active_record
create db/migrate/20120108151543_create_authors.rb
create app/models/author.rb
instructions to create the authors table
the Author model