SlideShare a Scribd company logo
JavaScript & Associations
Joost / @yopefonic
Associations & JavaScript
JavaScript
JavaScript
JavaScript 
1. What it is 
2. Basic syntax 
3. Libraries 
4. in Rails 
5. Assignment
JavaScript / What
JavaScript / what 
Brendan Eich
JavaScript / what 
• 1995 
• web browsers 
• servers 
• runs on almost all machines
JavaScript / what 
Royal pain in the ass
JavaScript / what 
• DOM manipulation 
• AJAX 
• General
JavaScript / Basic syntax
JavaScript / Basic syntax 
<!DOCTYPE html> 
<html> 
<head> 
<title>Some title</title> 
<script type=“text/javascript“ src=“/public/some_file.js“> 
</script> 
</head> 
<body> 
<!-- some content —> 
<script type=“text/javascript“> 
// your code 
</script> 
</body> 
</html>
JavaScript / Basic syntax 
// variables 
var x = 2; 
// functions 
var power = function (y) { 
return y*y; 
} 
// logging 
console.log( power(x) );
JavaScript / Basic syntax 
// there are some quirks 
(function(_this){ 
var hidden = ‘some hidden variable’; 
console.log( hidden ); 
_this.document.getElementById(“demo”).innerHTML = hidden; 
})(this);
JavaScript / Basic syntax 
2.toString(); // raises SyntaxError 
(2).toString(); // returns “2“ 
var girl = { name: ‘Martina‘ } 
girl.1234; // raises SyntaxError 
girl['1234']; // works 
[] + []; // returns ““ 
[] + {}; // returns [object Object] 
{} + []; // returns 0 
{} + {}; // returns NaN
JavaScript / Basic syntax
JavaScript / Basic syntax 
Brendan Eich
JavaScript / Basic syntax
JavaScript / Libraries
JavaScript / Libraries 
• Dojo Toolkit 
• MooTools 
• YUI Library 
• Node.js 
• Socket.io 
• Ext JS 
• Script.aculo.us 
• AngularJS 
• Ember.js 
• Backbone.js
JavaScript / Libraries
JavaScript / Libraries / jQuery 
// native 
document.getElementById(“demo“).innerHTML = “Hello World“; 
// jQuery 
$(“#demo“).text(“Hello World“);
JavaScript / Libraries / jQuery 
// select tag 
$(“p“) 
// select ID 
$(“#demo“) 
// select Class 
$(“.demo .foobar“) 
// select Attribute 
$(“[data-attibute=‘value’]“)
JavaScript / Libraries / jQuery 
// events 
$(“a[href=‘/demo‘]“).on(“click“, function( event ){ 
event.preventDefault(); 
alert(“link is not being followed”); 
});
JavaScript / Libraries
JavaScript / Libraries / underscore.js 
// iteration 
var array = [‘foo‘, ‘bar‘, ‘baz‘]; 
// native 
for (var i = 0; i < array.length; i++) { 
alert(array[i]); 
} 
// underscore 
_.each(array, alert);
JavaScript / Libraries
JavaScript / in Rails
JavaScript / in Rails / Layout 
// In the layout <head> 
<%= javascript_include_tag 
'application', 
'data-turbolinks-track' => true %>
JavaScript / in Rails
JavaScript / in Rails / Sprockets 
// require files 
//= require jquery 
//= require jquery_ujs 
//= require turbolinks 
// require folder 
//= require_tree .
JavaScript / in Rails
JavaScript / in Rails / CoffeeScript 
// JavaScript 
var square = function(x) { 
return x * x; 
}; 
// CoffeeScript 
square = (x) -> x * x
JavaScript / in Rails / CoffeeScript 
// JavaScript 
typeof elvis !== "undefined" && elvis !== null 
// CoffeeScript 
elvis?
JavaScript / in Rails / CoffeeScript 
// JavaScript bad comparators 
0 == ‘’ 
true == 1 
null == undefined 
false != ‘false’ 
// JavaScript good comparators 
0 !== ‘’ 
true !== 1 
null !== undefined 
false !== ‘false’
JavaScript / in Rails / CoffeeScript 
// CoffeeScript saves 
0 != ‘’ 
true != 1 
null != undefined 
false != ‘false’
JavaScript / Assignments 
• As a user I want to show errors 
on my author creation form 
before I submit the form so I 
know if the name is a valid 
one. 
• As a user I want to be able to 
preview my post with a 
separate button so I can see 
how it will look before I actually 
save the post.
Intermission
Associations
Associations
Associations 
1. modeling 
2. one to many 
3. many to many 
4. dependencies 
5. deep relations 
6. assignments
Associations / Modeling
Associations / Modeling 
Author 
name 
Post 
title 
body 
Category 
name
Associations / Modeling 
Author 
name 
Post 
title 
body 
Category 
name 
1 
0..*
Associations / Modeling 
Author 
name 
Post 
title 
body 
author_id 
Category 
name 
1 
0..*
Associations / Modeling 
Author 
name 
Post 
title 
body 
author_id 
Category 
name 
1 
0..* 
0..* 0..*
Associations / Modeling 
Author 
name 
Post 
title 
body 
author_id 
Category 
name 
1 
0..* 
0..* 
CategoryPost 
post_id 
category_id 
1 
0..* 
1
Associations / One to Many
Associations / One to many 
Author 
name 
Post 
title 
body 
author_id 
1 
0..*
Associations / One to many 
// create migration 
rails g migration AddAuthorIdToPost author_id:integer 
// run migration 
rake db:migrate
Associations / One to many 
// generated code 
class AddAuthorIdToPost < ActiveRecord::Migration 
def change 
add_column :posts, :author_id, :integer 
end 
end
Associations / One to many 
// add model code 
class Post < ActiveRecord::Base 
belongs_to :author 
end 
class Author < ActiveRecord::Base 
has_many :posts 
end
Associations / One to many 
// add model code 
class Post < ActiveRecord::Base 
belongs_to :author 
end 
class Author < ActiveRecord::Base 
has_one :post 
end
Associations / One to many 
// creating associations 
author = Auther.create name: ‘Joost’ 
author.posts.create title: ‘railsgirls #4’, body: ‘current 
course’ 
Post.create title: ‘railsgirls #5’, body: ‘new course’, 
author: author
Associations / Many to many
Associations / Many to many 
Post 
title 
body 
author_id 
Category 
name 
0..* 
PostCategory 
post_id 
category_id 
1 
0..* 
1
Associations / Many to many 
// create migration 
rails g migration create_categories_posts post_id:integer 
category_id:integer 
// run migration 
rake db:migrate
Associations / Many to many 
// generated code 
class CreateCategoriesPosts < ActiveRecord::Migration 
def change 
create_table :categories_posts do |t| 
t.integer :post_id 
t.integer :category_id 
end 
end 
end
Associations / Many to many 
// add model code 
class Post < ActiveRecord::Base 
has_and_belongs_to_many :categories 
end 
class Category < ActiveRecord::Base 
has_and_belongs_to_many :posts 
end
Associations / Many to many 
// creating associations 
post = Post.create title: ‘railsgirls #4’, body: ‘current 
course’ 
post.categories = [Category.create, Category.create] 
post.categories << Category.create name: ‘new category’
Associations / Dependencies
Associations / Dependencies 
Author 
Post Post
Associations / Dependencies 
// setting up dependencies 
class AuthorsController < ApplicationController 
def destroy 
@author.destroy 
respond_to do |format| 
format.html { redirect_to authors_url, notice: 'Author was 
successfully destroyed.' } 
format.json { head :no_content } 
end 
end 
end
Associations / Dependencies 
// setting up dependencies 
class AuthorsController < ApplicationController 
def destroy 
@author.posts.each do |post| 
post.destroy 
end 
@author.destroy 
respond_to do |format| 
format.html { redirect_to authors_url, notice: 'Author was 
successfully destroyed.' } 
format.json { head :no_content } 
end 
end 
end
Associations / Dependencies 
// setting up dependencies 
class Author < ActiveRecord::Base 
has_many :posts, dependent: :destroy 
end
Associations / Deep relations
Associations / Deep relations 
Author 
name 
Post 
title 
body 
author_id 
Category 
name 
1 
0..* 
0..* 
CategoryPost 
post_id 
category_id 
1 
0..* 
1
Associations / Deep relations 
// author’s categories 
@author.posts.collect(&:categories).flatten 
// more beautiful 
@author.categories
Associations / Deep relations 
// has_many :through 
class Author < ActiveRecord::Base 
has_many :posts 
has_many :categories, through: :posts 
end
Associations / Deep relations 
// one thing though 
@author.categories.uniq
Associations / Assignment
JavaScript / Assignments 
• As an author I want to be able 
to create a post from my page 
so that the post will be 
attached to my name. 
• As an author I want to be able 
to attach and detach categories 
on my posts so they are nicely 
labelled.

More Related Content

KEY
jQuery Performance Tips and Tricks (2011)
PPTX
SharePoint and jQuery Essentials
KEY
jQuery Anti-Patterns for Performance & Compression
PPTX
Javascript for the c# developer
PPTX
Put a little Backbone in your WordPress
PDF
Introduction to AngularJS For WordPress Developers
PPTX
JavaScript and jQuery Basics
PPTX
Jquery fundamentals
jQuery Performance Tips and Tricks (2011)
SharePoint and jQuery Essentials
jQuery Anti-Patterns for Performance & Compression
Javascript for the c# developer
Put a little Backbone in your WordPress
Introduction to AngularJS For WordPress Developers
JavaScript and jQuery Basics
Jquery fundamentals

What's hot (20)

PDF
Becoming a better WordPress Developer
PDF
Transformando os pepinos do cliente no código de testes da sua aplicação
PPTX
Getting the Most Out of jQuery Widgets
KEY
SproutCore is Awesome - HTML5 Summer DevFest
PPTX
Introduction to Plugin Programming, WordCamp Miami 2011
PDF
Ch. 8 script free pages
PDF
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
PPTX
Jquery Complete Presentation along with Javascript Basics
KEY
Custom Post Types in Depth at WordCamp Montreal
PDF
WordPress as the Backbone(.js)
PPTX
jQuery Presentation
PDF
Difference between java script and jquery
PDF
Finding Restfulness - Madrid.rb April 2014
PPT
Javascript and jQuery intro
PDF
Ch. 9 jsp standard tag library
KEY
Advanced WordPress Development Environments
PPTX
Test automation with selenide
PDF
Learn about Eclipse e4 from Lars Vogel at SF-JUG
PPTX
End-to-end testing with geb
PDF
MVS: An angular MVC
Becoming a better WordPress Developer
Transformando os pepinos do cliente no código de testes da sua aplicação
Getting the Most Out of jQuery Widgets
SproutCore is Awesome - HTML5 Summer DevFest
Introduction to Plugin Programming, WordCamp Miami 2011
Ch. 8 script free pages
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Jquery Complete Presentation along with Javascript Basics
Custom Post Types in Depth at WordCamp Montreal
WordPress as the Backbone(.js)
jQuery Presentation
Difference between java script and jquery
Finding Restfulness - Madrid.rb April 2014
Javascript and jQuery intro
Ch. 9 jsp standard tag library
Advanced WordPress Development Environments
Test automation with selenide
Learn about Eclipse e4 from Lars Vogel at SF-JUG
End-to-end testing with geb
MVS: An angular MVC
Ad

Similar to Associations & JavaScript (20)

PDF
Rails 3: Dashing to the Finish
KEY
Ruby/Rails
PDF
Rails 3 overview
PDF
Introduction à Ruby
PPT
68837.ppt
PDF
BP-6 Repository Customization Best Practices
PDF
Pourquoi ruby et rails déchirent
PDF
Mojolicious
PDF
Be happy with Ruby on Rails - CEUNSP Itu
PPTX
Beyond DOMReady: Ultra High-Performance Javascript
PDF
An Introduction to Tornado
PPT
Eugene Andruszczenko: jQuery
PPT
jQuery Presentation - Refresh Events
PPSX
RequireJS
KEY
[Coscup 2012] JavascriptMVC
PDF
jQuery and Rails: Best Friends Forever
PDF
Javascript MVC & Backbone Tips & Tricks
PDF
Web Components v1
PDF
Styling components with JavaScript
Rails 3: Dashing to the Finish
Ruby/Rails
Rails 3 overview
Introduction à Ruby
68837.ppt
BP-6 Repository Customization Best Practices
Pourquoi ruby et rails déchirent
Mojolicious
Be happy with Ruby on Rails - CEUNSP Itu
Beyond DOMReady: Ultra High-Performance Javascript
An Introduction to Tornado
Eugene Andruszczenko: jQuery
jQuery Presentation - Refresh Events
RequireJS
[Coscup 2012] JavascriptMVC
jQuery and Rails: Best Friends Forever
Javascript MVC & Backbone Tips & Tricks
Web Components v1
Styling components with JavaScript
Ad

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Tartificialntelligence_presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Encapsulation theory and applications.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Spectroscopy.pptx food analysis technology
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Machine Learning_overview_presentation.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
cuic standard and advanced reporting.pdf
Programs and apps: productivity, graphics, security and other tools
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Tartificialntelligence_presentation.pptx
MYSQL Presentation for SQL database connectivity
Encapsulation_ Review paper, used for researhc scholars
Encapsulation theory and applications.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Reach Out and Touch Someone: Haptics and Empathic Computing
Spectroscopy.pptx food analysis technology
NewMind AI Weekly Chronicles - August'25-Week II
Machine Learning_overview_presentation.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
A comparative analysis of optical character recognition models for extracting...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Assigned Numbers - 2025 - Bluetooth® Document
“AI and Expert System Decision Support & Business Intelligence Systems”

Associations & JavaScript

  • 6. JavaScript 1. What it is 2. Basic syntax 3. Libraries 4. in Rails 5. Assignment
  • 8. JavaScript / what Brendan Eich
  • 9. JavaScript / what • 1995 • web browsers • servers • runs on almost all machines
  • 10. JavaScript / what Royal pain in the ass
  • 11. JavaScript / what • DOM manipulation • AJAX • General
  • 13. JavaScript / Basic syntax <!DOCTYPE html> <html> <head> <title>Some title</title> <script type=“text/javascript“ src=“/public/some_file.js“> </script> </head> <body> <!-- some content —> <script type=“text/javascript“> // your code </script> </body> </html>
  • 14. JavaScript / Basic syntax // variables var x = 2; // functions var power = function (y) { return y*y; } // logging console.log( power(x) );
  • 15. JavaScript / Basic syntax // there are some quirks (function(_this){ var hidden = ‘some hidden variable’; console.log( hidden ); _this.document.getElementById(“demo”).innerHTML = hidden; })(this);
  • 16. JavaScript / Basic syntax 2.toString(); // raises SyntaxError (2).toString(); // returns “2“ var girl = { name: ‘Martina‘ } girl.1234; // raises SyntaxError girl['1234']; // works [] + []; // returns ““ [] + {}; // returns [object Object] {} + []; // returns 0 {} + {}; // returns NaN
  • 18. JavaScript / Basic syntax Brendan Eich
  • 21. JavaScript / Libraries • Dojo Toolkit • MooTools • YUI Library • Node.js • Socket.io • Ext JS • Script.aculo.us • AngularJS • Ember.js • Backbone.js
  • 23. JavaScript / Libraries / jQuery // native document.getElementById(“demo“).innerHTML = “Hello World“; // jQuery $(“#demo“).text(“Hello World“);
  • 24. JavaScript / Libraries / jQuery // select tag $(“p“) // select ID $(“#demo“) // select Class $(“.demo .foobar“) // select Attribute $(“[data-attibute=‘value’]“)
  • 25. JavaScript / Libraries / jQuery // events $(“a[href=‘/demo‘]“).on(“click“, function( event ){ event.preventDefault(); alert(“link is not being followed”); });
  • 27. JavaScript / Libraries / underscore.js // iteration var array = [‘foo‘, ‘bar‘, ‘baz‘]; // native for (var i = 0; i < array.length; i++) { alert(array[i]); } // underscore _.each(array, alert);
  • 30. JavaScript / in Rails / Layout // In the layout <head> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  • 32. JavaScript / in Rails / Sprockets // require files //= require jquery //= require jquery_ujs //= require turbolinks // require folder //= require_tree .
  • 34. JavaScript / in Rails / CoffeeScript // JavaScript var square = function(x) { return x * x; }; // CoffeeScript square = (x) -> x * x
  • 35. JavaScript / in Rails / CoffeeScript // JavaScript typeof elvis !== "undefined" && elvis !== null // CoffeeScript elvis?
  • 36. JavaScript / in Rails / CoffeeScript // JavaScript bad comparators 0 == ‘’ true == 1 null == undefined false != ‘false’ // JavaScript good comparators 0 !== ‘’ true !== 1 null !== undefined false !== ‘false’
  • 37. JavaScript / in Rails / CoffeeScript // CoffeeScript saves 0 != ‘’ true != 1 null != undefined false != ‘false’
  • 38. JavaScript / Assignments • As a user I want to show errors on my author creation form before I submit the form so I know if the name is a valid one. • As a user I want to be able to preview my post with a separate button so I can see how it will look before I actually save the post.
  • 42. Associations 1. modeling 2. one to many 3. many to many 4. dependencies 5. deep relations 6. assignments
  • 44. Associations / Modeling Author name Post title body Category name
  • 45. Associations / Modeling Author name Post title body Category name 1 0..*
  • 46. Associations / Modeling Author name Post title body author_id Category name 1 0..*
  • 47. Associations / Modeling Author name Post title body author_id Category name 1 0..* 0..* 0..*
  • 48. Associations / Modeling Author name Post title body author_id Category name 1 0..* 0..* CategoryPost post_id category_id 1 0..* 1
  • 50. Associations / One to many Author name Post title body author_id 1 0..*
  • 51. Associations / One to many // create migration rails g migration AddAuthorIdToPost author_id:integer // run migration rake db:migrate
  • 52. Associations / One to many // generated code class AddAuthorIdToPost < ActiveRecord::Migration def change add_column :posts, :author_id, :integer end end
  • 53. Associations / One to many // add model code class Post < ActiveRecord::Base belongs_to :author end class Author < ActiveRecord::Base has_many :posts end
  • 54. Associations / One to many // add model code class Post < ActiveRecord::Base belongs_to :author end class Author < ActiveRecord::Base has_one :post end
  • 55. Associations / One to many // creating associations author = Auther.create name: ‘Joost’ author.posts.create title: ‘railsgirls #4’, body: ‘current course’ Post.create title: ‘railsgirls #5’, body: ‘new course’, author: author
  • 57. Associations / Many to many Post title body author_id Category name 0..* PostCategory post_id category_id 1 0..* 1
  • 58. Associations / Many to many // create migration rails g migration create_categories_posts post_id:integer category_id:integer // run migration rake db:migrate
  • 59. Associations / Many to many // generated code class CreateCategoriesPosts < ActiveRecord::Migration def change create_table :categories_posts do |t| t.integer :post_id t.integer :category_id end end end
  • 60. Associations / Many to many // add model code class Post < ActiveRecord::Base has_and_belongs_to_many :categories end class Category < ActiveRecord::Base has_and_belongs_to_many :posts end
  • 61. Associations / Many to many // creating associations post = Post.create title: ‘railsgirls #4’, body: ‘current course’ post.categories = [Category.create, Category.create] post.categories << Category.create name: ‘new category’
  • 63. Associations / Dependencies Author Post Post
  • 64. Associations / Dependencies // setting up dependencies class AuthorsController < ApplicationController def destroy @author.destroy respond_to do |format| format.html { redirect_to authors_url, notice: 'Author was successfully destroyed.' } format.json { head :no_content } end end end
  • 65. Associations / Dependencies // setting up dependencies class AuthorsController < ApplicationController def destroy @author.posts.each do |post| post.destroy end @author.destroy respond_to do |format| format.html { redirect_to authors_url, notice: 'Author was successfully destroyed.' } format.json { head :no_content } end end end
  • 66. Associations / Dependencies // setting up dependencies class Author < ActiveRecord::Base has_many :posts, dependent: :destroy end
  • 67. Associations / Deep relations
  • 68. Associations / Deep relations Author name Post title body author_id Category name 1 0..* 0..* CategoryPost post_id category_id 1 0..* 1
  • 69. Associations / Deep relations // author’s categories @author.posts.collect(&:categories).flatten // more beautiful @author.categories
  • 70. Associations / Deep relations // has_many :through class Author < ActiveRecord::Base has_many :posts has_many :categories, through: :posts end
  • 71. Associations / Deep relations // one thing though @author.categories.uniq
  • 73. JavaScript / Assignments • As an author I want to be able to create a post from my page so that the post will be attached to my name. • As an author I want to be able to attach and detach categories on my posts so they are nicely labelled.