SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
Desenvolvimento
Web com Ruby on
Rails
João Lucas Pereira de Santana
gtalk | linkedin | twitter: jlucasps
Extras
Extras
@jlucasps
$ git add .
$ git commit -m "Configurando o Devise"
Criar rotas para BillsController#new
match 'new_bill' => 'bills#new', :as => :new_bill
match 'create_bill' => 'bills#create_bill', :as => :create_bill
Criar action
def new
@bill = Bill.new
@users = User.all
end
Extras
@jlucasps
Alterar template /app/views/welcome/index.html.erb
<div class="span9">
<% label = "<i class='icon-user'></i>&nbsp;#{t('users')}".html_safe
%>
<%= link_to label, users_path, :class => "btn btn-large" %>
<%= link_to t('new_bill'), new_bill_path, :class => "btn btn-
large btn-success" %>
</div>
<%= content_for :sidebar do %>
<%= render :partial => 'shared/sidebar' %>
<% end %>
Extras
@jlucasps
Criar template /app/views/bills/new.html.erb
<h4><%= t('new_bill') %></h4>
<%= form_tag(create_bill_path) do %>
<%= render :partial => 'shared/error_messages' , :locals => {:resource => @bill} %>
<%= label_tag :user_id %>
<%= select_tag :user_id, options_from_collection_for_select(@users, :id, :name, @bill.
user_id) %>
<%= label_tag :name %>
<%= text_field_tag :name, @bill.name %>
<%= label_tag :description %>
<%= text_field_tag :description, @bill.description %>
<%= label_tag :date %>
<%= text_field_tag :date, @bill.date %>
<%= label_tag :value %>
<%= text_field_tag :value, @bill.value %>
<div class='actions'>
<%= submit_tag t('save'), :class => 'btn btn-success' %>
</div>
<% end %>
Extras
@jlucasps
Criar a action BillsController#create_bill
def create_bill
@bill = Bill.new(:user_id => params[:user_id], :name =>
params[:name])
@bill.description = params[:description]
@bill.date = params[:date]
@bill.value = params[:value]
if @bill.save
redirect_to @bill.user
else
@users = User.all
render :new
end
end
Extras
@jlucasps
Criar uma migration para a tabela comments
class CreateTableComments < ActiveRecord::
Migration
def change
create_table :comments do |t|
t.references :bill, :foreign_key => true
t.column :content, :string, :null => false
t.timestamps
end
end
end
Extras
@jlucasps
Executar migration
jlucasps@lotus:/media/truecrypt1/handsonrails/first_app$ rake db:
migrate
== CreateTableComments: migrating
==========================================
==
-- create_table(:comments)
-> 0.0670s
== CreateTableComments: migrated (0.0672s)
===================================
Extras
@jlucasps
Criar model Comment: /app/models/comment.rb
class Comment < ActiveRecord::Base
# Attrs accessible
attr_accessible :content, :bill_id
# Validations
validates :content, :presence => true, :allow_blank => false
validates :bill_id, :presence => true
# Associations
belongs_to :bill
# Scopes
default_scope order("comments.created_at DESC")
# Públic methods
end
Extras
@jlucasps
Alterar model Bill para adicionar relacionamento
class Bill < ActiveRecord::Base
# Attrs accessible
attr_accessible :name, :description, :user_id, :date, :value
# Validations
validates :name, :presence => true, :allow_blank => false
validates :user_id, :presence => true
validates :date, :presence => true
validates :value, :presence => true
# Associations
belongs_to :user
has_many :comments
...
end
Extras
@jlucasps
irb(main):002:0> bill = Bill.first
Bill Load (0.5ms) SELECT "bills".* FROM "bills" ORDER BY bills.date
DESC LIMIT 1
=> #<Bill id: 15, name: "123", description: "45", user_id: 9, date:
"2013-06-12 00:00:00", value: #<BigDecimal:3bc4e60,'0.124E3',9(36)
>, created_at: "2013-06-19 01:17:36", updated_at: "2013-06-19 01:17:
36">
irb(main):003:0> comment = Comment.new :bill_id => bill.id, :
content => "Conteúdo do comentário"
=> #<Comment id: nil, bill_id: 15, content: "Conteúdo do comentário",
created_at: nil, updated_at: nil>
irb(main):004:0> comment.save
(0.1ms) begin transaction
SQL (43.4ms) INSERT INTO "comments" ("bill_id", "content",
"created_at", "updated_at") VALUES (?, ?, ?, ?) [["bill_id", 15],
["content", "Conteúdo do comentário"], ["created_at", Tue, 25 Jun 2013
14:30:13 UTC +00:00], ["updated_at", Tue, 25 Jun 2013 14:30:13 UTC
+00:00]]
(393.4ms) commit transaction
Extras
@jlucasps
irb(main):005:0> bill.comments
Comment Load (0.4ms) SELECT "comments".* FROM "comments"
WHERE "comments"."bill_id" = 15 ORDER BY comments.created_at
DESC
=> [#<Comment id: 1, bill_id: 15, content: "Conteúdo do comentário",
created_at: "2013-06-25 14:30:13", updated_at: "2013-06-25 14:30:
13">]
irb(main):006:0> bill.comments.count
(0.3ms) SELECT COUNT(*) FROM "comments" WHERE "comments"."
bill_id" = 15
=> 1
irb(main):007:0> comment.bill
Bill Load (0.4ms) SELECT "bills".* FROM "bills" WHERE "bills"."id" = 15
ORDER BY bills.date DESC LIMIT 1
=> #<Bill id: 15, name: "123", description: "45", user_id: 9, date:
"2013-06-12 00:00:00", value: #<BigDecimal:42d7f68,'0.124E3',9(36)
>, created_at: "2013-06-19 01:17:36", updated_at: "2013-06-19 01:
17:36">
irb(main):008:0>
Extras
@jlucasps
E se quisermos adicionar comentários em outras entidades ?
jlucasps@lotus:/media/truecrypt1/handsonrails/first_app$ rails g migration
ChangeCommentsTable
invoke active_record
create db/migrate/20130625143912_change_comments_table.rb
class ChangeCommentsTable < ActiveRecord::Migration
def up
add_column :comments, :commentable_id, :integer
add_column :comments, :commentable_type, :string
remove_column :comments, :bill_id
end
def down
remove_column :comments, :commentable_id
remove_column :comments, :commentable_type
add_column :comments, :bill_id, :integer
end
end
Extras
@jlucasps
class Comment < ActiveRecord::Base
# Attrs accessible
attr_accessible :content, :bill_id
# Validations
validates :content, :presence => true, :allow_blank => false
validates :commentable_id, :presence => true
validates :commentable_type, :presence => true
# Associations
belongs_to :commentable, :polymorphic => true
# Scopes
default_scope order("comments.created_at DESC")
end
/app/models/comment.rb
Extras
@jlucasps
# Associations
belongs_to :user
has_many :comments, :as => :commentable
/app/models/bill.rb
/app/models/user.rb
# Associations
has_many :bills, :dependent => :destroy
has_many :comments, :as => :commentable
Extras
@jlucasps
jlucasps@lotus:/media/truecrypt1/handsonrails/first_app$ rails
console
Loading development environment (Rails 3.2.13)
irb(main):002:0> user = User.last
User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY "users"."
id" DESC LIMIT 1
=> #<User id: 11, name: "teste100@teste.com", email:
"teste100@teste.com", age: nil, created_at: "2013-06-25 01:27:25",
updated_at: "2013-06-25 01:27:25", gender: nil, encrypted_password:
"$2a$10$hMAd4RUymIzxw1JGARKJC.M1hEiAwD0PpwS6uwM9j2RR...",
reset_password_token: nil, reset_password_sent_at: nil,
remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2013-
06-25 01:27:25", last_sign_in_at: "2013-06-25 01:27:25",
current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1">
irb(main):003:0> user.comments
Comment Load (0.2ms) SELECT "comments".* FROM "comments"
WHERE "comments"."commentable_id" = 11 AND "comments"."
commentable_type" = 'User' ORDER BY comments.created_at DESC
=> []
irb(main):004:0>
Extras
@jlucasps
irb(main):003:0> comment = Comment.new :content =>
"Comentário para um usuário"
=> #<Comment id: nil, content: "Comentário para um usuário",
created_at: nil, updated_at: nil, commentable_id: nil, commentable_type:
nil>
irb(main):004:0> comment.commentable = user
=> #<User id: 11, name: "teste100@teste.com", email: "teste100@teste.com", age: nil,
created_at: "2013-06-25 01:27:25", updated_at: "2013-06-25 01:27:25", gender: nil,
encrypted_password: "$2a$10$hMAd4RUymIzxw1JGARKJC.M1hEiAwD0PpwS6uwM9j2RR...",
reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil,
sign_in_count: 1, current_sign_in_at: "2013-06-25 01:27:25", last_sign_in_at: "2013-06-25
01:27:25", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1">
irb(main):005:0> comment.save
(0.1ms) begin transaction
SQL (63.5ms) INSERT INTO "comments" ("commentable_id", "commentable_type", "content",
"created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["commentable_id", 11],
["commentable_type", "User"], ["content", "Comentário para um usuário"], ["created_at", Tue,
25 Jun 2013 17:39:18 UTC +00:00], ["updated_at", Tue, 25 Jun 2013 17:39:18 UTC +00:
00]]
(405.1ms) commit transaction
=> true
Extras
@jlucasps
irb(main):008:0> bill = Bill.first
Bill Load (0.4ms) SELECT "bills".* FROM "bills" ORDER BY bills.date DESC LIMIT 1
=> #<Bill id: 15, name: "123", description: "45", user_id: 9, date: "2013-06-12 00:00:00", value:
#<BigDecimal:43384f8,'0.124E3',9(36)>, created_at: "2013-06-19 01:17:36", updated_at: "2013-
06-19 01:17:36">
irb(main):009:0> comment_2 = Comment.new :content => "Comentário
de uma conta"
=> #<Comment id: nil, content: "Comentário de uma conta", created_at: nil, updated_at: nil,
commentable_id: nil, commentable_type: nil>
irb(main):011:0> comment_2.commentable = bill
=> #<Bill id: 15, name: "123", description: "45", user_id: 9, date: "2013-06-12 00:00:00", value:
#<BigDecimal:41fbae0,'0.124E3',9(36)>, created_at: "2013-06-19 01:17:36", updated_at: "2013-
06-19 01:17:36">
irb(main):012:0> comment_2.save
(0.1ms) begin transaction
SQL (0.7ms) INSERT INTO "comments" ("commentable_id", "commentable_type", "content",
"created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["commentable_id", 15], ["commentable_type",
"Bill"], ["content", "Comentário de uma conta"], ["created_at", Tue, 25 Jun 2013 17:44:17 UTC
+00:00], ["updated_at", Tue, 25 Jun 2013 17:44:17 UTC +00:00]]
(430.8ms) commit transaction
=> true
irb(main):013:0> bill.comments
Comment Load (0.4ms) SELECT "comments".* FROM "comments" WHERE "comments"."
commentable_id" = 15 AND "comments"."commentable_type" = 'Bill' ORDER BY comments.
created_at DESC
=> [#<Comment id: 3, content: "Comentário de uma conta", created_at: "2013-06-25 17:44:17",
updated_at: "2013-06-25 17:44:17", commentable_id: 15, commentable_type: "Bill">]
Extras
@jlucasps
irb(main):014:0> comment.commentable
=> #<User id: 11, name: "teste100@teste.com", email:
"teste100@teste.com", age: nil, created_at: "2013-06-25 01:27:25",
updated_at: "2013-06-25 01:27:25", gender: nil, encrypted_password:
"$2a$10$hMAd4RUymIzxw1JGARKJC.M1hEiAwD0PpwS6uwM9j2RR...",
reset_password_token: nil, reset_password_sent_at: nil,
remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2013-
06-25 01:27:25", last_sign_in_at: "2013-06-25 01:27:25",
current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1">
irb(main):015:0> comment_2.commentable
=> #<Bill id: 15, name: "123", description: "45", user_id: 9, date:
"2013-06-12 00:00:00", value: #<BigDecimal:3ed9268,'0.124E3',9(36)
>, created_at: "2013-06-19 01:17:36", updated_at: "2013-06-19 01:17:
36">
irb(main):016:0>
Desenvolvimento
Web com Ruby on
Rails
João Lucas Pereira de Santana
gtalk | linkedin | twitter: jlucasps
Obrigado!

Weitere ähnliche Inhalte

Was ist angesagt?

前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJSZhang Xiaoxue
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoRob Bontekoe
 
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and BeautifulBefore there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and Beautifulchicagonewsonlineradio
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
Desenvolvimento web com Ruby on Rails (parte 5)
Desenvolvimento web com Ruby on Rails (parte 5)Desenvolvimento web com Ruby on Rails (parte 5)
Desenvolvimento web com Ruby on Rails (parte 5)Joao Lucas Santana
 
EmberConf 2015 – Ambitious UX for Ambitious Apps
EmberConf 2015 – Ambitious UX for Ambitious AppsEmberConf 2015 – Ambitious UX for Ambitious Apps
EmberConf 2015 – Ambitious UX for Ambitious AppsLauren Elizabeth Tan
 
WebApps e Frameworks Javascript
WebApps e Frameworks JavascriptWebApps e Frameworks Javascript
WebApps e Frameworks Javascriptmeet2Brains
 
The rise and fall of a techno DJ, plus more new reviews and notable screenings
The rise and fall of a techno DJ, plus more new reviews and notable screeningsThe rise and fall of a techno DJ, plus more new reviews and notable screenings
The rise and fall of a techno DJ, plus more new reviews and notable screeningschicagonewsyesterday
 
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...tdc-globalcode
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
Clickable DIVs and other icebergs
Clickable DIVs and other icebergsClickable DIVs and other icebergs
Clickable DIVs and other icebergsBen Buchanan
 
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013Joao Lucas Santana
 
Authentication
AuthenticationAuthentication
Authenticationsoon
 
JavaScript Testing for Rubyists
JavaScript Testing for RubyistsJavaScript Testing for Rubyists
JavaScript Testing for RubyistsJamie Dyer
 

Was ist angesagt? (19)

前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJS
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 
course js day 3
course js day 3course js day 3
course js day 3
 
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and BeautifulBefore there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
Desenvolvimento web com Ruby on Rails (parte 5)
Desenvolvimento web com Ruby on Rails (parte 5)Desenvolvimento web com Ruby on Rails (parte 5)
Desenvolvimento web com Ruby on Rails (parte 5)
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
 
Micro app-framework
Micro app-frameworkMicro app-framework
Micro app-framework
 
EmberConf 2015 – Ambitious UX for Ambitious Apps
EmberConf 2015 – Ambitious UX for Ambitious AppsEmberConf 2015 – Ambitious UX for Ambitious Apps
EmberConf 2015 – Ambitious UX for Ambitious Apps
 
WebApps e Frameworks Javascript
WebApps e Frameworks JavascriptWebApps e Frameworks Javascript
WebApps e Frameworks Javascript
 
The rise and fall of a techno DJ, plus more new reviews and notable screenings
The rise and fall of a techno DJ, plus more new reviews and notable screeningsThe rise and fall of a techno DJ, plus more new reviews and notable screenings
The rise and fall of a techno DJ, plus more new reviews and notable screenings
 
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Clickable DIVs and other icebergs
Clickable DIVs and other icebergsClickable DIVs and other icebergs
Clickable DIVs and other icebergs
 
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
 
Authentication
AuthenticationAuthentication
Authentication
 
JavaScript Testing for Rubyists
JavaScript Testing for RubyistsJavaScript Testing for Rubyists
JavaScript Testing for Rubyists
 
Android query
Android queryAndroid query
Android query
 

Andere mochten auch

Curso de Ruby on Rails - Aula 04
Curso de Ruby on Rails - Aula 04Curso de Ruby on Rails - Aula 04
Curso de Ruby on Rails - Aula 04Maurício Linhares
 
Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Joao Lucas Santana
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Joao Lucas Santana
 
Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)Joao Lucas Santana
 
Consultation on 16 19 vocational reform fa qs (5)
Consultation on 16 19 vocational reform fa qs (5)Consultation on 16 19 vocational reform fa qs (5)
Consultation on 16 19 vocational reform fa qs (5)amyclaire
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Joao Lucas Santana
 
Servidores de E-mail: Qmail, Sendmail e Postfix
Servidores de E-mail: Qmail, Sendmail e PostfixServidores de E-mail: Qmail, Sendmail e Postfix
Servidores de E-mail: Qmail, Sendmail e PostfixAlvaro Oliveira
 

Andere mochten auch (7)

Curso de Ruby on Rails - Aula 04
Curso de Ruby on Rails - Aula 04Curso de Ruby on Rails - Aula 04
Curso de Ruby on Rails - Aula 04
 
Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
 
Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)Desenvolvimento web com Ruby on Rails (parte 3)
Desenvolvimento web com Ruby on Rails (parte 3)
 
Consultation on 16 19 vocational reform fa qs (5)
Consultation on 16 19 vocational reform fa qs (5)Consultation on 16 19 vocational reform fa qs (5)
Consultation on 16 19 vocational reform fa qs (5)
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)
 
Servidores de E-mail: Qmail, Sendmail e Postfix
Servidores de E-mail: Qmail, Sendmail e PostfixServidores de E-mail: Qmail, Sendmail e Postfix
Servidores de E-mail: Qmail, Sendmail e Postfix
 

Ähnlich wie Desenvolvimento web com Ruby on Rails (extras)

Controller Testing: You're Doing It Wrong
Controller Testing: You're Doing It WrongController Testing: You're Doing It Wrong
Controller Testing: You're Doing It Wrongjohnnygroundwork
 
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxSH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxMongoDB
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”apostlion
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Rabble .
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Rails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power StackRails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power StackDavid Copeland
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysqlKnoldus Inc.
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsSalesforce Developers
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB
 
Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg...
 Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg... Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg...
Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg...Brian Mann
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
Rails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowRails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowChris Oliver
 

Ähnlich wie Desenvolvimento web com Ruby on Rails (extras) (20)

Controller Testing: You're Doing It Wrong
Controller Testing: You're Doing It WrongController Testing: You're Doing It Wrong
Controller Testing: You're Doing It Wrong
 
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxSH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Rails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power StackRails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power Stack
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Active record(1)
Active record(1)Active record(1)
Active record(1)
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
 
Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg...
 Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg... Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg...
Little Opinions, Big Possibilities: The Tools and Patterns for Building Larg...
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
Rails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowRails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not Know
 

Kürzlich hochgeladen

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 

Kürzlich hochgeladen (20)

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 

Desenvolvimento web com Ruby on Rails (extras)

  • 1. Desenvolvimento Web com Ruby on Rails João Lucas Pereira de Santana gtalk | linkedin | twitter: jlucasps Extras
  • 2. Extras @jlucasps $ git add . $ git commit -m "Configurando o Devise" Criar rotas para BillsController#new match 'new_bill' => 'bills#new', :as => :new_bill match 'create_bill' => 'bills#create_bill', :as => :create_bill Criar action def new @bill = Bill.new @users = User.all end
  • 3. Extras @jlucasps Alterar template /app/views/welcome/index.html.erb <div class="span9"> <% label = "<i class='icon-user'></i>&nbsp;#{t('users')}".html_safe %> <%= link_to label, users_path, :class => "btn btn-large" %> <%= link_to t('new_bill'), new_bill_path, :class => "btn btn- large btn-success" %> </div> <%= content_for :sidebar do %> <%= render :partial => 'shared/sidebar' %> <% end %>
  • 4. Extras @jlucasps Criar template /app/views/bills/new.html.erb <h4><%= t('new_bill') %></h4> <%= form_tag(create_bill_path) do %> <%= render :partial => 'shared/error_messages' , :locals => {:resource => @bill} %> <%= label_tag :user_id %> <%= select_tag :user_id, options_from_collection_for_select(@users, :id, :name, @bill. user_id) %> <%= label_tag :name %> <%= text_field_tag :name, @bill.name %> <%= label_tag :description %> <%= text_field_tag :description, @bill.description %> <%= label_tag :date %> <%= text_field_tag :date, @bill.date %> <%= label_tag :value %> <%= text_field_tag :value, @bill.value %> <div class='actions'> <%= submit_tag t('save'), :class => 'btn btn-success' %> </div> <% end %>
  • 5. Extras @jlucasps Criar a action BillsController#create_bill def create_bill @bill = Bill.new(:user_id => params[:user_id], :name => params[:name]) @bill.description = params[:description] @bill.date = params[:date] @bill.value = params[:value] if @bill.save redirect_to @bill.user else @users = User.all render :new end end
  • 6. Extras @jlucasps Criar uma migration para a tabela comments class CreateTableComments < ActiveRecord:: Migration def change create_table :comments do |t| t.references :bill, :foreign_key => true t.column :content, :string, :null => false t.timestamps end end end
  • 7. Extras @jlucasps Executar migration jlucasps@lotus:/media/truecrypt1/handsonrails/first_app$ rake db: migrate == CreateTableComments: migrating ========================================== == -- create_table(:comments) -> 0.0670s == CreateTableComments: migrated (0.0672s) ===================================
  • 8. Extras @jlucasps Criar model Comment: /app/models/comment.rb class Comment < ActiveRecord::Base # Attrs accessible attr_accessible :content, :bill_id # Validations validates :content, :presence => true, :allow_blank => false validates :bill_id, :presence => true # Associations belongs_to :bill # Scopes default_scope order("comments.created_at DESC") # Públic methods end
  • 9. Extras @jlucasps Alterar model Bill para adicionar relacionamento class Bill < ActiveRecord::Base # Attrs accessible attr_accessible :name, :description, :user_id, :date, :value # Validations validates :name, :presence => true, :allow_blank => false validates :user_id, :presence => true validates :date, :presence => true validates :value, :presence => true # Associations belongs_to :user has_many :comments ... end
  • 10. Extras @jlucasps irb(main):002:0> bill = Bill.first Bill Load (0.5ms) SELECT "bills".* FROM "bills" ORDER BY bills.date DESC LIMIT 1 => #<Bill id: 15, name: "123", description: "45", user_id: 9, date: "2013-06-12 00:00:00", value: #<BigDecimal:3bc4e60,'0.124E3',9(36) >, created_at: "2013-06-19 01:17:36", updated_at: "2013-06-19 01:17: 36"> irb(main):003:0> comment = Comment.new :bill_id => bill.id, : content => "Conteúdo do comentário" => #<Comment id: nil, bill_id: 15, content: "Conteúdo do comentário", created_at: nil, updated_at: nil> irb(main):004:0> comment.save (0.1ms) begin transaction SQL (43.4ms) INSERT INTO "comments" ("bill_id", "content", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["bill_id", 15], ["content", "Conteúdo do comentário"], ["created_at", Tue, 25 Jun 2013 14:30:13 UTC +00:00], ["updated_at", Tue, 25 Jun 2013 14:30:13 UTC +00:00]] (393.4ms) commit transaction
  • 11. Extras @jlucasps irb(main):005:0> bill.comments Comment Load (0.4ms) SELECT "comments".* FROM "comments" WHERE "comments"."bill_id" = 15 ORDER BY comments.created_at DESC => [#<Comment id: 1, bill_id: 15, content: "Conteúdo do comentário", created_at: "2013-06-25 14:30:13", updated_at: "2013-06-25 14:30: 13">] irb(main):006:0> bill.comments.count (0.3ms) SELECT COUNT(*) FROM "comments" WHERE "comments"." bill_id" = 15 => 1 irb(main):007:0> comment.bill Bill Load (0.4ms) SELECT "bills".* FROM "bills" WHERE "bills"."id" = 15 ORDER BY bills.date DESC LIMIT 1 => #<Bill id: 15, name: "123", description: "45", user_id: 9, date: "2013-06-12 00:00:00", value: #<BigDecimal:42d7f68,'0.124E3',9(36) >, created_at: "2013-06-19 01:17:36", updated_at: "2013-06-19 01: 17:36"> irb(main):008:0>
  • 12. Extras @jlucasps E se quisermos adicionar comentários em outras entidades ? jlucasps@lotus:/media/truecrypt1/handsonrails/first_app$ rails g migration ChangeCommentsTable invoke active_record create db/migrate/20130625143912_change_comments_table.rb class ChangeCommentsTable < ActiveRecord::Migration def up add_column :comments, :commentable_id, :integer add_column :comments, :commentable_type, :string remove_column :comments, :bill_id end def down remove_column :comments, :commentable_id remove_column :comments, :commentable_type add_column :comments, :bill_id, :integer end end
  • 13. Extras @jlucasps class Comment < ActiveRecord::Base # Attrs accessible attr_accessible :content, :bill_id # Validations validates :content, :presence => true, :allow_blank => false validates :commentable_id, :presence => true validates :commentable_type, :presence => true # Associations belongs_to :commentable, :polymorphic => true # Scopes default_scope order("comments.created_at DESC") end /app/models/comment.rb
  • 14. Extras @jlucasps # Associations belongs_to :user has_many :comments, :as => :commentable /app/models/bill.rb /app/models/user.rb # Associations has_many :bills, :dependent => :destroy has_many :comments, :as => :commentable
  • 15. Extras @jlucasps jlucasps@lotus:/media/truecrypt1/handsonrails/first_app$ rails console Loading development environment (Rails 3.2.13) irb(main):002:0> user = User.last User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY "users"." id" DESC LIMIT 1 => #<User id: 11, name: "teste100@teste.com", email: "teste100@teste.com", age: nil, created_at: "2013-06-25 01:27:25", updated_at: "2013-06-25 01:27:25", gender: nil, encrypted_password: "$2a$10$hMAd4RUymIzxw1JGARKJC.M1hEiAwD0PpwS6uwM9j2RR...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2013- 06-25 01:27:25", last_sign_in_at: "2013-06-25 01:27:25", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1"> irb(main):003:0> user.comments Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = 11 AND "comments"." commentable_type" = 'User' ORDER BY comments.created_at DESC => [] irb(main):004:0>
  • 16. Extras @jlucasps irb(main):003:0> comment = Comment.new :content => "Comentário para um usuário" => #<Comment id: nil, content: "Comentário para um usuário", created_at: nil, updated_at: nil, commentable_id: nil, commentable_type: nil> irb(main):004:0> comment.commentable = user => #<User id: 11, name: "teste100@teste.com", email: "teste100@teste.com", age: nil, created_at: "2013-06-25 01:27:25", updated_at: "2013-06-25 01:27:25", gender: nil, encrypted_password: "$2a$10$hMAd4RUymIzxw1JGARKJC.M1hEiAwD0PpwS6uwM9j2RR...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2013-06-25 01:27:25", last_sign_in_at: "2013-06-25 01:27:25", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1"> irb(main):005:0> comment.save (0.1ms) begin transaction SQL (63.5ms) INSERT INTO "comments" ("commentable_id", "commentable_type", "content", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["commentable_id", 11], ["commentable_type", "User"], ["content", "Comentário para um usuário"], ["created_at", Tue, 25 Jun 2013 17:39:18 UTC +00:00], ["updated_at", Tue, 25 Jun 2013 17:39:18 UTC +00: 00]] (405.1ms) commit transaction => true
  • 17. Extras @jlucasps irb(main):008:0> bill = Bill.first Bill Load (0.4ms) SELECT "bills".* FROM "bills" ORDER BY bills.date DESC LIMIT 1 => #<Bill id: 15, name: "123", description: "45", user_id: 9, date: "2013-06-12 00:00:00", value: #<BigDecimal:43384f8,'0.124E3',9(36)>, created_at: "2013-06-19 01:17:36", updated_at: "2013- 06-19 01:17:36"> irb(main):009:0> comment_2 = Comment.new :content => "Comentário de uma conta" => #<Comment id: nil, content: "Comentário de uma conta", created_at: nil, updated_at: nil, commentable_id: nil, commentable_type: nil> irb(main):011:0> comment_2.commentable = bill => #<Bill id: 15, name: "123", description: "45", user_id: 9, date: "2013-06-12 00:00:00", value: #<BigDecimal:41fbae0,'0.124E3',9(36)>, created_at: "2013-06-19 01:17:36", updated_at: "2013- 06-19 01:17:36"> irb(main):012:0> comment_2.save (0.1ms) begin transaction SQL (0.7ms) INSERT INTO "comments" ("commentable_id", "commentable_type", "content", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["commentable_id", 15], ["commentable_type", "Bill"], ["content", "Comentário de uma conta"], ["created_at", Tue, 25 Jun 2013 17:44:17 UTC +00:00], ["updated_at", Tue, 25 Jun 2013 17:44:17 UTC +00:00]] (430.8ms) commit transaction => true irb(main):013:0> bill.comments Comment Load (0.4ms) SELECT "comments".* FROM "comments" WHERE "comments"." commentable_id" = 15 AND "comments"."commentable_type" = 'Bill' ORDER BY comments. created_at DESC => [#<Comment id: 3, content: "Comentário de uma conta", created_at: "2013-06-25 17:44:17", updated_at: "2013-06-25 17:44:17", commentable_id: 15, commentable_type: "Bill">]
  • 18. Extras @jlucasps irb(main):014:0> comment.commentable => #<User id: 11, name: "teste100@teste.com", email: "teste100@teste.com", age: nil, created_at: "2013-06-25 01:27:25", updated_at: "2013-06-25 01:27:25", gender: nil, encrypted_password: "$2a$10$hMAd4RUymIzxw1JGARKJC.M1hEiAwD0PpwS6uwM9j2RR...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2013- 06-25 01:27:25", last_sign_in_at: "2013-06-25 01:27:25", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1"> irb(main):015:0> comment_2.commentable => #<Bill id: 15, name: "123", description: "45", user_id: 9, date: "2013-06-12 00:00:00", value: #<BigDecimal:3ed9268,'0.124E3',9(36) >, created_at: "2013-06-19 01:17:36", updated_at: "2013-06-19 01:17: 36"> irb(main):016:0>
  • 19. Desenvolvimento Web com Ruby on Rails João Lucas Pereira de Santana gtalk | linkedin | twitter: jlucasps Obrigado!