A Guide to Active Record Associations
This guide covers the association features of Active Record. By referring to this guide, you will be able to:
-
Declare associations between Active Record models
-
Understand the various types of Active Record associations
-
Use the methods added to your models by creating associations
1. Why Associations?
Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
class Customer < ActiveRecord::Base end class Order < ActiveRecord::Base end
Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
@orders =<EMAIL_ADDRESS>@orders.each do |order| order.destroy end @customer.destroy
With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
class Customer < ActiveRecord::Base has_many :orders end class Order < ActiveRecord::Base belongs_to :customer end
With this change, creating a new order for a particular customer is easier:
@order = @customer.orders.create(:order_date => Time.now)
Deleting a customer and all of its orders is much easier:
@customer.destroy
To learn more about the different types of associations, read the next section of this Guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
2. The Types of Associations
In Rails, an association is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model belongs_to another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
-
belongs_to
-
has_one
-
has_many
-
has_many :through
-
has_one :through
-
has_and_belongs_to_many
In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
2.1. The belongs_to Association
A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
class Order < ActiveRecord::Base belongs_to :customer end
2.2. The has_one Association
A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
class Supplier < ActiveRecord::Base has_one :account end
2.3. The has_many Association
A has_many association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
class Customer < ActiveRecord::Base has_many :orders end
| The name of the other model is pluralized when declaring a has_many association. |
2.4. The has_many :through Association
A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
class Physician < ActiveRecord::Base has_many :appointments has_many :patients, :through => :appointments end class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end class Patient < ActiveRecord::Base has_many :appointments has_many :physicians, :through => :appointments end
The has_many :through association is also useful for setting up "shortcuts" through nested :has_many associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
class Document < ActiveRecord::Base has_many :sections has_many :paragraphs, :through => :sections end class Section < ActiveRecord::Base belongs_to :document has_many :paragraphs end class Paragraph < ActiveRecord::Base belongs_to :section end
2.5. The has_one :through Association
A has_one :through association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding through a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
class Supplier < ActiveRecord::Base has_one :account has_one :account_history, :through => :account end class Account < ActiveRecord::Base belongs_to :supplier has_one :account_history end class AccountHistory < ActiveRecord::Base belongs_to :account end
2.6. The has_and_belongs_to_many Association
A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
class Assembly < ActiveRecord::Base has_and_belongs_to_many :parts end class Part < ActiveRecord::Base has_and_belongs_to_many :assemblies end
2.7. Choosing Between belongs_to and has_one
If you want to set up a 1-1 relationship between two models, you'll need to add belongs_to to one, and has_one to the other. How do you know which is which?
The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well. The has_one relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
class Supplier < ActiveRecord::Base has_one :account end class Account < ActiveRecord::Base belongs_to :supplier end
The corresponding migration might look like this:
class CreateSuppliers < ActiveRecord::Migration def self.up create_table :suppliers do |t| t.string :name t.timestamps end create_table :accounts do |t| t.integer :supplier_id t.string :account_number t.timestamps end end def self.down drop_table :accounts drop_table :suppliers end end
| Using t.integer :supplier_id makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using t.references :supplier instead. |
2.8. Choosing Between has_many :through and has_and_belongs_to_many
Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use has_and_belongs_to_many, which allows you to make the association directly:
class Assembly < ActiveRecord::Base has_and_belongs_to_many :parts end class Part < ActiveRecord::Base has_and_belongs_to_many :assemblies end
The second way to declare a many-to-many relationship is to use has_many :through. This makes the association indirectly, through a join model:
class Assembly < ActiveRecord::Base has_many :manifests has_many :parts, :through => :manifests end class Manifest < ActiveRecord::Base belongs_to :assembly belongs_to :part end class Part < ActiveRecord::Base has_many :manifests has_many :assemblies, :through => :manifests end
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table).
You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.
2.9. Polymorphic Associations
A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
class Picture < ActiveRecord::Base belongs_to :imageable, :polymorphic => true end class Employee < ActiveRecord::Base has_many :pictures, :as => :imageable end class Product < ActiveRecord::Base has_many :pictures, :as => :imageable end
You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use. From an instance of the Employee model, you can retrieve a collection of pictures: @employee.pictures. Similarly, you can retrieve @product.pictures. If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
class CreatePictures < ActiveRecord::Migration def self.up create_table :pictures do |t| t.string :name t.integer :imageable_id t.string :imageable_type t.timestamps end end def self.down drop_table :pictures end end
This migration can be simplified by using the t.references form:
class CreatePictures < ActiveRecord::Migration def self.up create_table :pictures do |t| t.string :name t.references :imageable, :polymorphic => true t.timestamps end end def self.down drop_table :pictures end end
2.10. Self Joins
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:
class Employee < ActiveRecord::Base has_many :subordinates, :class_name => "User", :foreign_key => "manager_id" belongs_to :manager, :class_name => "User" end
With this setup, you can retrieve @employee.subordinates and @employee.managers.
3. Tips, Tricks, and Warnings
Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
-
Controlling caching
-
Avoiding name collisions
-
Updating the schema
-
Controlling association scope
3.1. Controlling Caching
All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
customer.orders # retrieves orders from the database customer.orders.size # uses the cached copy of orders customer.orders.empty? # uses the cached copy of orders
But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass true to the association call:
customer.orders # retrieves orders from the database customer.orders.size # uses the cached copy of orders customer.orders(true).empty? # discards the cached copy of orders and goes back to the database
3.2. Avoiding Name Collisions
You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of ActiveRecord::Base. The association method would override the base method and break things. For instance, attributes or connection are bad names for associations.
3.3. Updating the Schema
Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:
class Order < ActiveRecord::Base belongs_to :customer end
This declaration needs to be backed up by the proper foreign key declaration on the orders table:
class CreateOrders < ActiveRecord::Migration def self.up create_table :orders do |t| t.order_date :datetime t.order_number :string t.customer_id :integer end end def self.down drop_table :orders end end
If you create an association some time after you build the underlying model, you need to remember to create an add_column migration to provide the necessary foreign key.
Second, if you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
| The precedence between model names is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers". |
Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
class Assembly < ActiveRecord::Base has_and_belongs_to_many :parts end class Part < ActiveRecord::Base has_and_belongs_to_many :assemblies end
These need to be backed up by a migration to create the assemblies_parts table. This table should be created without a primary key:
class CreateAssemblyPartJoinTable < ActiveRecord::Migration def self.up create_table :assemblies_parts, :id => false do |t| t.integer :assembly_id t.integer :part_id end end def self.down drop_table :assemblies_parts end end
3.4. Controlling Association Scope
By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account end class Account < ActiveRecord::Base belongs_to :supplier end end end
This will work fine, because both the Supplier and the Account class are defined within the same scope. But this will not work, because Supplier and Account are defined in different scopes:
module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account end end module Billing class Account < ActiveRecord::Base belongs_to :supplier end end end
To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:
module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account, :class_name => "MyApplication::Billing::Account" end end module Billing class Account < ActiveRecord::Base belongs_to :supplier, :class_name => "MyApplication::Business::Supplier" end end end
4. Detailed Association Reference
The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
4.1. The belongs_to Association
The belongs_to association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use has_one instead.
4.1.1. Methods Added by belongs_to
When you declare a belongs_to assocation, the declaring class automatically gains five methods related to the association:
-
association(force_reload = false)
-
association=(associate)
-
association.nil?
-
build_association(attributes = {})
-
create_association(attributes = {})
In all of these methods, association is replaced with the symbol passed as the first argument to belongs_to. For example, given the declaration:
class Order < ActiveRecord::Base belongs_to :customer end
Each instance of the order model will have these methods:
customer customer= customer.nil? build_customer create_customer
association(force_reload = false)
The association method returns the associated object, if any. If no associated object is found, it returns nil.
@customer = @order.customer
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass true as the force_reload argument.
association=(associate)
The association= method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
@order.customer = @customer
association.nil?
The association.nil? method returns true if there is no associated object.
if @order.customer.nil? @msg = "No customer found for this order" end
build_association(attributes = {})
The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
@customer = @order.build_customer({:customer_number => 123, :customer_name => "John Doe"})
create_association(attributes = {})
The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
@customer = @order.create_customer({:customer_number => 123, :customer_name => "John Doe"})
4.1.2. Options for belongs_to
In many situations, you can use the default behavior of belongs_to without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a belongs_to association. For example, an association with several options might look like this:
class Order < ActiveRecord::Base belongs_to :customer, :counter_cache => true, :conditions => "active = 1" end
The belongs_to association supports these options:
-
:class_name
-
:conditions
-
:counter_cache
-
:dependent
-
:foreign_key
-
:include
-
:polymorphic
-
:readonly
-
:select
-
:validate
:class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is Patron, you'd set things up this way:
class Order < ActiveRecord::Base belongs_to :customer, :class_name => "Patron" end
:conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
class Order < ActiveRecord::Base belongs_to :customer, :conditions => "active = 1" end
:counter_cache
The :counter_cache option can be used to make finding the number of belonging objects more efficient. Consider these models:
class Order < ActiveRecord::Base belongs_to :customer end class Customer < ActiveRecord::Base has_many :orders end
With these declarations, asking for the value of @customer.orders.size requires making a call to the database to perform a COUNT(*) query. To avoid this call, you can add a counter cache to the belonging model:
class Order < ActiveRecord::Base belongs_to :customer, :counter_cache => true end class Customer < ActiveRecord::Base has_many :orders end
With this declaration, Rails will keep the cache value up to date, and then return that value in response to the .size method.
Although the :counter_cache option is specified on the model that includes the belongs_to declaration, the actual column must be added to the associated model. In the case above, you would need to add a column named orders_count to the Customer model. You can override the default column name if you need to:
class Order < ActiveRecord::Base belongs_to :customer, :counter_cache => :count_of_orders end class Customer < ActiveRecord::Base has_many :orders end
Counter cache columns are added to the containing model's list of read-only attributes through attr_readonly.
:dependent
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method.
| You should not specify this option on a belongs_to association that is connected with a has_many association on the other class. Doing so can lead to orphaned records in your database. |
:foreign_key
By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class Order < ActiveRecord::Base belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id" end
| In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. |
:include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
class LineItem < ActiveRecord::Base belongs_to :order end class Order < ActiveRecord::Base belongs_to :customer has_many :line_items end class Customer < ActiveRecord::Base has_many :orders end
If you frequently retrieve customers directly from line items (@line_item.order.customer), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
class LineItem < ActiveRecord::Base belongs_to :order, :include => :customer end class Order < ActiveRecord::Base belongs_to :customer has_many :line_items end class Customer < ActiveRecord::Base has_many :orders end
| There's no need to use :include for immediate associations - that is, if you have Order belongs_to :customer, then the customer is eager-loaded automatically when it's needed. |
:polymorphic
Passing true to the :polymorphic option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
:readonly
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
:select
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
:validate
If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.
4.1.3. When are Objects Saved?
Assigning an object to a belongs_to association does not automatically save the object. It does not save the associated object either.
4.2. The has_one Association
The has_one association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use belongs_to instead.
4.2.1. Methods Added by has_one
When you declare a has_one association, the declaring class automatically gains five methods related to the association:
-
association(force_reload = false)
-
association=(associate)
-
association.nil?
-
build_association(attributes = {})
-
create_association(attributes = {})
In all of these methods, association is replaced with the symbol passed as the first argument to has_one. For example, given the declaration:
class Supplier < ActiveRecord::Base has_one :account end
Each instance of the Supplier model will have these methods:
account account= account.nil? build_account create_account
association(force_reload = false)
The association method returns the associated object, if any. If no associated object is found, it returns nil.
@account = @supplier.account
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass true as the force_reload argument.
association=(associate)
The association= method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
@suppler.account = @account
association.nil?
The association.nil? method returns true if there is no associated object.
if @supplier.account.nil? @msg = "No account found for this supplier" end
build_association(attributes = {})
The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
@account = @supplier.build_account({:terms => "Net 30"})
create_association(attributes = {})
The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
@account = @supplier.create_account({:terms => "Net 30"})
4.2.2. Options for has_one
In many situations, you can use the default behavior of has_one without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_one association. For example, an association with several options might look like this:
class Supplier < ActiveRecord::Base has_one :account, :class_name => "Billing", :dependent => :nullify end
The has_one association supports these options:
-
:as
-
:class_name
-
:conditions
-
:dependent
-
:foreign_key
-
:include
-
:order
-
:primary_key
-
:readonly
-
:select
-
:source
-
:source_type
-
:through
-
:validate
:as
Setting the :as option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
:class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way:
class Supplier < ActiveRecord::Base has_one :account, :class_name => "Billing" end
:conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
class Supplier < ActiveRecord::Base has_one :account, :conditions => "confirmed = 1" end
:dependent
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the association object to NULL.
:foreign_key
By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class Supplier < ActiveRecord::Base has_one :account, :foreign_key => "supp_id" end
| In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. |
:include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
class Supplier < ActiveRecord::Base has_one :account end class Account < ActiveRecord::Base belongs_to :supplier belongs_to :representative end class Representative < ActiveRecord::Base has_many :accounts end
If you frequently retrieve representatives directly from suppliers (@supplier.account.representative), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
class Supplier < ActiveRecord::Base has_one :account, :include => :representative end class Account < ActiveRecord::Base belongs_to :supplier belongs_to :representative end class Representative < ActiveRecord::Base has_many :accounts end
:order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause). Because a has_one association will only retrieve a single associated object, this option should not be needed.
:primary_key
By convention, Rails guesses that the column used to hold the primary key of this model is id. You can override this and explicitly specify the primary key with the :primary_key option.
:readonly
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
:select
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
:source
The :source option specifies the source association name for a has_one :through association.
:source_type
The :source_type option specifies the source association type for a has_one :through association that proceeds through a polymorphic association.
:through
The :through option specifies a join model through which to perform the query. has_one :through associations are discussed in detail later in this guide.
:validate
If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.
4.2.3. When are Objects Saved?
When you assign an object to a has_one association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
If either of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
If the parent object (the one declaring the has_one association) is unsaved (that is, new_record? returns true) then the child objects are not saved.
If you want to assign an object to a has_one association without saving the object, use the association.build method.
4.3. The has_many Association
The has_many association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
4.3.1. Methods Added
When you declare a has_many association, the declaring class automatically gains 13 methods related to the association:
-
collection(force_reload = false)
-
collection<<(object, …)
-
collection.delete(object, …)
-
collection=objects
-
collection_singular_ids
-
collection_singular_ids=ids
-
collection.clear
-
collection.empty?
-
collection.size
-
collection.find(…)
-
collection.exist?(…)
-
collection.build(attributes = {}, …)
-
collection.create(attributes = {})
In all of these methods, collection is replaced with the symbol passed as the first argument to has_many, and collection_singular is replaced with the singularized version of that symbol.. For example, given the declaration:
class Customer < ActiveRecord::Base has_many :orders end
Each instance of the customer model will have these methods:
orders(force_reload = false) orders<<(object, ...) orders.delete(object, ...) orders=objects order_ids order_ids=ids orders.clear orders.empty? orders.size orders.find(...) orders.exist?(...) orders.build(attributes = {}, ...) orders.create(attributes = {})
collection(force_reload = false)
The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
@orders = @customer.orders
collection<<(object, …)
The collection<< method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
@customer.orders << @order1
collection.delete(object, …)
The collection.delete method removes one or more objects from the collection by setting their foreign keys to NULL.
@customer.orders.delete(@order1)
| Objects will be in addition destroyed if they're associated with :dependent ⇒ :destroy, and deleted if they're associated with :dependent ⇒ :delete_all. |
collection=objects
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
collection_singular_ids
The collection_singular_ids method returns an array of the ids of the objects in the collection.
@order_ids = @customer.order_ids
_collection_singular_ids=ids
The _collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
collection.clear
The collection.clear method removes every object from the collection. This destroys the associated objects if they are associated with :dependent ⇒ :destroy, deletes them directly from the database if :dependent ⇒ :delete_all, and otherwise sets their foreign keys to NULL.
collection.empty?
The collection.empty? method returns true if the collection does not contain any associated objects.
<% if @customer.orders.empty? %> No Orders Found <% end %>
collection.size
The collection.size method returns the number of objects in the collection.
@order_count = @customer.orders.size
collection.find(…)
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find.
@open_orders = @customer.orders.find(:all, :conditions => "open = 1")
collection.exist?(…)
The collection.exist? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.
collection.build(attributes = {}, …)
The collection.build method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will not yet be saved.
@order = @customer.orders.build({:order_date => Time.now, :order_number => "A12345"})
collection.create(attributes = {})
The collection.create method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object will be saved (assuming that it passes any validations).
@order = @customer.orders.create({:order_date => Time.now, :order_number => "A12345"})
4.3.2. Options for has_many
In many situations, you can use the default behavior for has_many without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_many association. For example, an association with several options might look like this:
class Customer < ActiveRecord::Base has_many :orders, :dependent => :delete_all, :validate => :false end
The has_many association supports these options:
-
:as
-
:class_name
-
:conditions
-
:counter_sql
-
:dependent
-
:extend
-
:finder_sql
-
:foreign_key
-
:group
-
:include
-
:limit
-
:offset
-
:order
-
:primary_key
-
:readonly
-
:select
-
:source
-
:source_type
-
:through
-
:uniq
-
:validate
:as
Setting the :as option indicates that this is a polymorphic association, as discussed earlier in this guide.
:class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is Transaction, you'd set things up this way:
class Customer < ActiveRecord::Base has_many :orders, :class_name => "Transaction" end
:conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
class Customer < ActiveRecord::Base has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1" end
You can also set conditions via a hash:
class Customer < ActiveRecord::Base has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true } end
If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @customer.confirmed_orders.create or @customer.confirmed_orders.build will create orders where the confirmed column has the value true.
:counter_sql
Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.
| If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT(*) FROM for the SELECT … FROM clause of your :finder_sql statement. |
:dependent
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the :dependent option to :delete_all, then deleting this object will delete the associated objects without calling their destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the associated objects to NULL.
| This option is ignored when you use the :through option on the association. |
:extend
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
:finder_sql
Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
:foreign_key
By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class Customer < ActiveRecord::Base has_many :orders, :foreign_key => "cust_id" end
| In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. |
:group
The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.
class Customer < ActiveRecord::Base has_many :line_items, :through => :orders, :group => "orders.id" end
:include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
class Customer < ActiveRecord::Base has_many :orders end class Order < ActiveRecord::Base belongs_to :customer has_many :line_items end class LineItem < ActiveRecord::Base belongs_to :order end
If you frequently retrieve line items directly from customers (@customer.orders.line_items), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
class Customer < ActiveRecord::Base has_many :orders, :include => :line_items end class Order < ActiveRecord::Base belongs_to :customer has_many :line_items end class LineItem < ActiveRecord::Base belongs_to :order end
:limit
The :limit option lets you restrict the total number of objects that will be fetched through an association.
class Customer < ActiveRecord::Base has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100 end
:offset
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.
:order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).
class Customer < ActiveRecord::Base has_many :orders, :order => "date_confirmed DESC" end
:primary_key
By convention, Rails guesses that the column used to hold the primary key of this model is id. You can override this and explicitly specify the primary key with the :primary_key option.
:readonly
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
:select
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
| If you specify your own :select, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error. |
:source
The :source option specifies the source association name for a has_many :through association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
:source_type
The :source_type option specifies the source association type for a has_many :through association that proceeds through a polymorphic association.
:through
The :through option specifies a join model through which to perform the query. has_many :through associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
:uniq
Specify the :uniq ⇒ true option to remove duplicates from the collection. This is most useful in conjunction with the :through option.
:validate
If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.
4.3.3. When are Objects Saved?
When you assign an object to a has_many association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
If the parent object (the one declaring the has_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
If you want to assign an object to a has_many association without saving the object, use the collection.build method.
4.4. The has_and_belongs_to_many Association
The has_and_belongs_to_many association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
4.4.1. Methods Added
When you declare a has_and_belongs_to_many association, the declaring class automatically gains 13 methods related to the association:
-
collection(force_reload = false)
-
collection<<(object, …)
-
collection.delete(object, …)
-
collection=objects
-
collection_singular_ids
-
collection_singular_ids=ids
-
collection.clear
-
collection.empty?
-
collection.size
-
collection.find(…)
-
collection.exist?(…)
-
collection.build(attributes = {})
-
collection.create(attributes = {})
In all of these methods, collection is replaced with the symbol passed as the first argument to has_many, and collection_singular is replaced with the singularized version of that symbol.. For example, given the declaration:
class Part < ActiveRecord::Base has_and_belongs_to_many :assemblies end
Each instance of the part model will have these methods:
assemblies(force_reload = false) assemblies<<(object, ...) assemblies.delete(object, ...) assemblies=objects assembly_ids assembly_ids=ids assemblies.clear assemblies.empty? assemblies.size assemblies.find(...) assemblies.exist?(...) assemblies.build(attributes = {}, ...) assemblies.create(attributes = {})
Additional Column Methods
If the join table for a has_and_belongs_to_many association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
| The use of extra attributes on the join table in a has_and_belongs_to_many association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a has_many :through association instead of has_and_belongs_to_many. |
collection(force_reload = false)
The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
@assemblies = @part.assemblies
collection<<(object, …)
The collection<< method adds one or more objects to the collection by creating records in the join table.
@part.assemblies << @assembly1
| This method is aliased as collection.concat and collection.push. |
collection.delete(object, …)
The collection.delete method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
@part.assemblies.delete(@assembly1)
collection=objects
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
collection_singular_ids
# Returns an array of the associated objects' ids
The collection_singular_ids method returns an array of the ids of the objects in the collection.
@assembly_ids = @part.assembly_ids
collection_singular_ids=ids
The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
collection.clear
The collection.clear method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.
collection.empty?
The collection.empty? method returns true if the collection does not contain any associated objects.
<% if @part.assemblies.empty? %> This part is not used in any assemblies <% end %>
collection.size
The collection.size method returns the number of objects in the collection.
@assembly_count = @part.assemblies.size
collection.find(…)
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find. It also adds the additional condition that the object must be in the collection.
@new_assemblies = @part.assemblies.find(:all, :conditions => ["created_at > ?", 2.days.ago])
collection.exist?(…)
The collection.exist? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.
collection.build(attributes = {})
The collection.build method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will not yet be saved.
@assembly = @part.assemblies.build({:assembly_name => "Transmission housing"})
collection.create(attributes = {})
The collection.create method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object will be saved (assuming that it passes any validations).
@assembly = @part.assemblies.create({:assembly_name => "Transmission housing"})
4.4.2. Options for has_and_belongs_to_many
In many situations, you can use the default behavior for has_and_belongs_to_many without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a has_and_belongs_to_many association. For example, an association with several options might look like this:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :uniq => true, :read_only => true end
The has_and_belongs_to_many association supports these options:
-
:association_foreign_key
-
:class_name
-
:conditions
-
:counter_sql
-
:delete_sql
-
:extend
-
:finder_sql
-
:foreign_key
-
:group
-
:include
-
:insert_sql
-
:join_table
-
:limit
-
:offset
-
:order
-
:readonly
-
:select
-
:uniq
-
:validate
:association_foreign_key
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix _id added. The :association_foreign_key option lets you set the name of the foreign key directly:
| The :foreign_key and :association_foreign_key options are useful when setting up a many-to-many self-join. For example: |
class User < ActiveRecord::Base has_and_belongs_to_many :friends, :class_name => "User", :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" end
:class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is Gadget, you'd set things up this way:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :class_name => "Gadget" end
:conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'" end
You can also set conditions via a hash:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' } end
If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @parts.assemblies.create or @parts.assemblies.build will create orders where the factory column has the value "Seattle".
:counter_sql
Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.
| If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT(*) FROM for the SELECT … FROM clause of your :finder_sql statement. |
:delete_sql
Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the :delete_sql option, you can specify a complete SQL statement to delete them yourself.
:extend
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
:finder_sql
Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
:foreign_key
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class User < ActiveRecord::Base has_and_belongs_to_many :friends, :class_name => "User", :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" end
:group
The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :group => "factory" end
:include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
:insert_sql
Normally Rails automatically generates the proper SQL to create links between the associated classes. With the :insert_sql option, you can specify a complete SQL statement to insert them yourself.
:join_table
If the default name of the join table, based on lexical ordering, is not what you want, you can use the :join_table option to override the default.
:limit
The :limit option lets you restrict the total number of objects that will be fetched through an association.
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :order => "created_at DESC", :limit => 50 end
:offset
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.
:order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :order => "assembly_name ASC" end
:readonly
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
:select
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
:uniq
Specify the :uniq ⇒ true option to remove duplicates from the collection.
:validate
If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.
4.4.3. When are Objects Saved?
When you assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
If the parent object (the one declaring the has_and_belongs_to_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
If you want to assign an object to a has_and_belongs_to_many association without saving the object, use the collection.build method.
4.5. Association Callbacks
Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a :before_save callback to cause something to happen just before an object is saved.
Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:
-
before_add
-
after_add
-
before_remove
-
after_remove
You define association callbacks by adding options to the association declaration. For example:
class Customer < ActiveRecord::Base has_many :orders, :before_add => :check_credit_limit def check_credit_limit(order) ... end end
Rails passes the object being added or removed to the callback.
You can stack callbacks on a single event by passing them as an array:
class Customer < ActiveRecord::Base has_many :orders, :before_add => [:check_credit_limit, :calculate_shipping_charges] def check_credit_limit(order) ... end def calculate_shipping_charges(order) ... end end
If a before_add callback throws an exception, the object does not get added to the collection. Similarly, if a before_remove callback throws an exception, the object does not get removed from the collection.
4.6. Association Extensions
You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
class Customer < ActiveRecord::Base has_many :orders do def find_by_order_prefix(order_number) find_by_region_id(order_number[0..2]) end end end
If you have an extension that should be shared by many associations, you can use a named extension module. For example:
module FindRecentExtension def find_recent find(:all, :conditions => ["created_at > ?", 5.days.ago]) end end class Customer < ActiveRecord::Base has_many :orders, :extend => FindRecentExtension end class Supplier < ActiveRecord::Base has_many :deliveries, :extend => FindRecentExtension end
To include more than one extension module in a single association, specify an array of names:
class Customer < ActiveRecord::Base has_many :orders, :extend => [FindRecentExtension, FindActiveExtension] end
Extensions can refer to the internals of the association proxy using these three accessors:
-
proxy_owner returns the object that the association is a part of.
-
proxy_reflection returns the reflection object that describes the association.
-
proxy_target returns the associated object for belongs_to or has_one, or the collection of associated objects for has_many or has_and_belongs_to_many.
5. Changelog
-
September 28, 2008: Corrected has_many :through diagram, added polymorphic diagram, some reorganization by Mike Gunderloy . First release version.
-
September 22, 2008: Added diagrams, misc. cleanup by Mike Gunderloy (not yet approved for publication)
-
September 14, 2008: initial version by Mike Gunderloy (not yet approved for publication)


Who am I
I am a Navy Vetern and software developer sipretium quis, sem. Nulla consequat massa quis enim.
Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.
Degrees
Advance fullstack development from Codefellows
Applied Science from Seattle Central collage
Avation machanic fron Naval Air School
Honors
1st place in Seattle Hackthon
Graduated with dean list from Seattle center collage
Graduated with honors from garfield high school
CV- Kerry park
- The Museum of flight
- safeco field
- Mt Rainer
- Museum of Pop culture
- Arboretum park
- Seattle public Library
- Fremont Mischief Distillery
- Union Station
- North Bend


AWS::IAM::InstanceProfile
The AWS::IAM::InstanceProfile
resource creates an AWS Identity and Access Management (IAM) instance
profile that can be used with IAM roles for EC2 instances.
For more information about IAM roles, see Working with Roles in the AWS Identity and Access Management User Guide.
Topics
Syntax
To declare this entity in your AWS CloudFormation template, use the following syntax:
JSON
{ "Type": "AWS::IAM::InstanceProfile", "Properties": { "Path":
String
, "Roles": [IAM Roles
], "InstanceProfileName":String
} }
YAML
Type: AWS::IAM::InstanceProfile Properties: Path:
String
Roles: -IAM Roles
InstanceProfileName:String
Properties
Path
-
The path associated with this IAM instance profile. For information about IAM paths, see Friendly Names and Paths in the AWS Identity and Access Management User Guide.
By default, AWS CloudFormation specifies
/
for the path.Required: No
Type: String
Update requires: Replacement
Roles
-
The name of an existing IAM role to associate with this instance profile. Currently, you can assign a maximum of one role to an instance profile.
Required: Yes
Type: List of String values
Update requires: No interruption
InstanceProfileName
-
The name of the instance profile that you want to create. This parameter allows (per its regex pattern) a string consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters:
= , . @ -
.Required: No
Type: String
Update requires: Replacement
Return Values
Ref
When the logical ID of this resource is provided to the Ref
intrinsic
function, Ref
returns the resource name. For example:
{ "Ref": "
MyProfile
" }
For the IAM::InstanceProfile
with the logical ID MyProfile
,
Ref
returns the resource name.
For more information about using the Ref
function, see Ref.
Fn::GetAtt
Fn::GetAtt
returns a value for a specified attribute of this type.
The following are the available attributes and sample return values.
Arn
-
Returns the Amazon Resource Name (ARN) for the instance profile. For example:
{"Fn::GetAtt" : ["
MyProfile
", "Arn"] }This returns a value such as
“arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ”
.
For more information about using Fn::GetAtt
, see Fn::GetAtt.


.
Home
Portfolio
Blog
State by State Models
Michigan
Experiments
Wisconsin
API
2020 Ratings
About
Contact
Richard's Stocks
Portfolio:
+110%, +$145,100
Value: $276,900 Invested $131,800
Updates: Portfolio Writeup, Thoughts on UBER, BYND, WE
Ticker
Company
Price
Avg Cost
Bought
PresentV
Initial
Yield
Yield Pct
PurchaseDate
Sector
TWTR
Twitter
$40.60
$14.55
5,250
$213,040
$76,400
+$136,600
+178%
June 2016
Tech
BYND
Beyond Meat
$81.90
$144.70
84
$6,880
$12,150
+$5,275
+76%
July 2019
Consumer
CAT
Caterpillar
$116.40
$92.15
72
$8,380
$6,640
+$1,750
+26%
Mar 2017
Construction
SNAP
Snapchat
$15.98
$11.49
600
$6,800
$9,580
+$2,690
+39%
May 2019
Tech
UBER
Uber
$35.20
$39.80
550
$19,300
$21,900
-$2,520
-11.4%
July 2019
Tech
WAL
Walmart
$113.00
$95.70
68
$7,680
$6,500
+$1,175
+18%
May 2018
Retail
CME
Chicago Exch
$213.60
$158.50
5
$1,070
$790
+$280
+34%
May 2019
Financials
DPZ
Dominos
$235.00
$245.40
24
$5640
$5890
-$250
+4.2%
May 2019
Consumer
Last Updated: Aug 29 2019


|
AbstractActor
|
|
Actor
|
|
ActorBuilder
|
|
ActorBuilder.Matcher
|
|
ActorBuilder.MatchingActor
|
|
ActorDoNothing
|
|
ActorRef
|
|
CanSchedule
|
|
Context
|
|
ContextBuilder
|
|
CreateException
|
|
DeadLetter
|
|
Disposable
|
|
DisposedException
|
|
Mailbox
|
|
MailboxFactory
|
|
Message
|
|
OnStopException
|
|
PoisonPill
|
|
PreStartException
|
|
Scheduler
|
|
SupervisedActorRef
|
|
Supervisor
|
|
Worker
|


Functions for working with Client objects
- Source:
Members
(inner) KEY_SPLITTER :string
The value used to separate client information in a PresenceKey
Type:
- string
- Source:
Methods
(static) create(socket) → {Promise.<Client>}
Create a new Client.
Parameters:
| Name | Type | Description |
|---|---|---|
socket |
WS.WebSocket | The socket that the new client is connected on |
- Source:
Returns:
A promise resolving with a new Client
- Type
- Promise.<Client>
Example
Client.create(webSocket).then(client => console.log(client));
(static) getPresenceKey(client) → {string}
Get the Redis presence key for a client.
Parameters:
| Name | Type | Description |
|---|---|---|
client |
Client | The client to fetch the presence key for |
- Source:
Returns:
A presence key for a client
- Type
- string
Example
Client.getPresenceKey(client);
// 'longhouse/spaces/spaceID/clientId/clientIdentity/2015-06-05T20:51:47.411Z'
(static) parsePresenceKey(presenceKey) → {Client}
Parse a presence key for Client info
Parameters:
| Name | Type | Description |
|---|---|---|
presenceKey |
string | A presence key |
- Source:
Returns:
A client
- Type
- Client
Example
Client.parsePresenceKey('longhouse/spaces/spaceID/clientId/clientIdentity/2015-06-05T20:51:47.411Z');
// { id: 'clientID', identity: 'clientIdentity', spaceID: 'spaceID', joinedAt: '2015-06-05T20:51:47.411Z' }
(static) serialize(client)
Serialize a client for sending to another client.
Parameters:
| Name | Type | Description |
|---|---|---|
client |
Client | The client to serialize |
- Source:
Example
Client.serialize(client);
// { id: 'clientID', identity: 'clientIdentity', joinedAt: '2015-06-05T20:51:47.411Z' }
Type Definitions
Client
A representation of someone connected to a space over a WebSocket connection
Type:
- object
Properties:
| Name | Type | Attributes | Description |
|---|---|---|---|
id |
string | The UUID identifying this client |
|
requestID |
string |
<nullable> |
The ID of the request this client connected with |
identity |
string | The identity value of this client (e.g. an email) |
|
spaceID |
string | The ID of the space this client is connected to |
|
socket |
WS.WebSocket | The socket the client is connected over |
|
joinedAt |
string | The time at which the client joined |
- Source:
PresenceKey
A key containing information about a connected client
The client information is all in the key, split by forward slashes:
longhouse/spaces/${spaceID}/${id}/${identity}/${joinedAt}
Type:
- string
- Source:


I Am sarika I completed my graduation in Electrical and Electronics Engineering at CMR College of Engineering and Technology.In my family we are 5 members Father,Mother,Me,Brother,Sister,My hobbies are singing and reading news paper.


{% extends "layout.html" %} {% block head %} {% endblock %} {% block body %}
In this page, you can investigate which phenotypes/variatns are important for principlal component {{ pc }}.
{{ phe_contribution_x | tojson | safe }}
{{ phe_contribution_y | tojson | safe }}
{{ phe_contribution_labels | tojson | safe }}
{{ var_contribution_x | tojson | safe }}
{{ var_contribution_y | tojson | safe }}
{{ var_contribution_labels | tojson | safe }}
We request that any use of data obtained from the Global Biobank Engine be cited in publications using the following format:
We also ask that the developers of the engine be acknowledged as follows:


Shells disambiguate (( differently or not at all. If the first ( should start a subshell, add a space after it.
See [[SC1102]], the similar warning for ambiguous $((.
$((


Hi, I need to write a program that alternates between parent and child, which the child printing first. I need to output Parent or Child, the pid, and a random Number. It compiles fine, but nothing outputs. Any help?
Thank you
int main(int argc, char *argv[])
{
// Declarations
int randomNumC, randomNumP;
int numOfRandomNumbers = atoi(argv[1]);
char childWritesToPipe[1], childReadsFromPipe[1];
char parentReadsFromPipe[1], parentWritesToPipe[1];
int pipe1[2];
int pipe2[2];
char character = 'T';
int index, count;
pipe(pipe1); // Creating my pipe
pipe(pipe2);
int pid = fork(); // Creating child process
srand(numOfRandomNumbers); // Getting seed
// For loop that will go through numOfRandomNumbers < 20
for(int i = 0; i < numOfRandomNumbers; i++)
{
if(pid < 0) // if pid is less then zero, there was an error
exit(1);
if(pid == 0)
{
srand(randomNumC); // Getting a different seed for Child Random Numbers
randomNumC = rand(); // Generating random number


All
Branding
Web
Photography
App
EXPLORE BEYOND HORIZON
Magna mundi referrentur quo, no rebum dignissim qui. Per quodsi accusata id, agam labores.
VIEW OUR WORK
view categories
All
Branding
Web
Photography
App
Show Me More


Audio misencoded in post-game interview with football coach Ed Orgeron
by Rob BeschizzaSports reporter Timothy Burke writes that "Something went wrong with my archival encode of the Utah State-LSU game, and all the audio is pitch-shifted down 100%. Which resulted in this."


Saturday parking free in Dec
by Colin DacreMotorists who want to do their Christmas shopping downtown Penticton next month will enjoy free parking on Saturdays.
City council this week approved no-charge street parking downtown on all four Saturdays in December. The municipality has run a similar program for the past several years, at request of the Downtown Penticton Association.
The city says waiving the parking fees will cost them about $5,000 in lost revenue.
A motion by Mayor John Vassilaki at Tuesday’s council meeting to have free transit on the same days failed, after a majority of councillors decided they wanted more information on the idea and will consider it next year.
Chief financial officer Jim Bauer said free transit would have cost the city an estimated less than $1,800 per day.


The example below shows how you can make complex tree structure using ag-Grid.
Notice that the data passed to the grid is already in a tree structure, it is not using the grids grouping functions to create the hierarchy.
Related sample in ag-grid docs


CrimPapers
Articles published on 19 January 2019
On 19 January 2019, 7 new articles were published in 6 journals.
Multi-Level Analysis of Disorder Policing and Fear of Crime in South Korea
Unravelling the ‘crimmigration Knot’: Penal Subjectivities, Punishment and the Censure Machine by Eleonora Di Molfetta, Jelmer Brouwer
“Like Make Up on A Man”: the Gendered Nature of Gun Norms by Christopher W. Mullins, Sou Lee
Survival Strategies While Engaging in Deviant Behaviors: the Case of Amateur Waterboarding Torture by Myles Balfe
‘i’m Not Sherlock Holmes’: Suspicions, Secrecy and Silence of Transplant Professionals in the Human Organ Trade by Frederike Ambagtsheer, Linde van Balen
Jonathan D., Rosen and Roberto Zepeda, Organised Crime, Drug Trafficking, and Violence (felipe Calderón to Enrique Peña Nieto) by Erik Cheekes
Frame-of-Reference Effects on Police Officer Applicant Responses to the Revised Neo Personality Inventory


Report of cougar attack triggers alert in Tri-Cities
by KEPR-TV News StaffKENNEWICK, Wash. - Law enforcement agencies are on alert after a woman reported her dog was attacked by a cougar in Kennewick.
The woman called 911 at about 11:20 p.m. Monday and said she was walking her dog when a cougar jumped out of tree, grabbed the dog and took off with it, according to the Benton County Sheriff's Office.
Deputies were unable to find the cougar or dog after the reported attack.
The attack happened on the corner of North Arthur Street and West Tucannon Avenue in Kennewick.
Sheriff's officials say they have alerted the Washington State Patrol of a potential dangerous cougar in the area.


Founded in 1898, the Budapest University Athletics Club , BEAC, the University of Budapest, and ELTE have been open to citizens interested in active and healthy lifestyles for more than a hundred years. It would be prove to be of great interest for anyone who loves to take part in physical education which helps maintain a healthy lifestyle. The website also provides information regarding the various sports and tournaments that one might be interested in.
You can apply to sports available from the given list and participate in it according to the schedule. Each and every sport has a specified trainer and venue for it.
You can regiser for course by following the steps below.
1. Log in to http://neptun.elte.hu NEPTUN.
2. Under the "Subjects" tab, select "Register for subject" menu.
3. On the Register for subject page, select the current term and the "Subject type: All subjects" option.
4. Also make sure, that "Subjects currently offered only:" is checked.
5. Write "VTN-" to the "Subject code" field and click on the "List subjects" button.
6. Choose the sport course you want to attend.
7. Click on Register!
https://elteonline.hu/sport/elte-beac/
Step 1
Step 2
Step 3
Step 4


Grameen Bank (Bengali: গ্রামীণ বাংক) is a microfinance organisation and community development bank founded in Bangladesh. It makes small loans (known as microcredit or "grameencredit")[7] to the impoverished without requiring collateral. Grameen Bank originated in 1976, in the work of Professor Muhammad Yunus at University of Chittagong, who launched a research project to study how to design a credit delivery system to provide banking services to the rural poor. In October 1983 the Grameen Bank was authorised by national legislation to operate as an independent bank. The bank grew significantly between 2003 and 2007. As of January 2011, the total borrowers of the bank number 8.4 million, and 97% of those are women.[8] In 1998 the Bank's "Low-cost Housing Program" won a World Habitat Award. In 2006, the bank and its founder, Muhammad Yunus, were jointly awarded the Nobel Peace Prize.[9] Type Body Corporate (Bank Law)[1] Industry Financial services Founded October 1983 Founder Muhammad Yunus Headquarters Dhaka, Bangladesh Number of locations 2,568 branches (January 2018)[2] Area served Bangladesh Key people Abul Khair Md. Monirul Hoque (Acting managing director)[3] Products Microfinance Revenue Increase ৳12.436 billion (US$150 million)(2010)[4] Operating income Increase ৳8.514 billion (US$100 million) (2010)[4] Net income Increase ৳75.73 crore (US$9.0 million) (2010)[4] Total assets ৳125.4 billion (US$1.5 billion) (2010)[5] Number of employees 20,138 '(January 2018)[6] Website grameen.com


{% extends 'keg-login/base.html' %} {% from "keg-login/macros.html" import render_change_password_form with context %}b {% block main %} {{ render_change_password_form(form) }} {% endblock %}


Class: Layout::LinearDimension
| Relationships | |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Class Chain:
self,
Entity
|
|
|
Instance Chain:
self,
Entity
|
|
| Inherits: |
Layout::Entity
|
Overview
References a linear dimension entity. A LinearDimension
is composed of the following sub-entities:
-
two ‘extension lines’ that connect to the
Entity
being dimensioned. -
a ‘dimension line’ connecting the ends of the leaders. This may be represented by one or two
Path
s depending on appearance. -
an optional ‘leader line’ that is used for small
LinearDimension
s. -
a ‘dimension text’ that displays the
LinearDimension
‘s text.
There are six points that may be modified for a LinearDimension
:
-
two ‘connection points’ that define the start and end of the
LinearDimension
. -
two ‘extent points’ that define the start and end of the dimension line and are the ends of the two extension lines.
-
two ‘offset points’ that define the starting points of the extension lines.
Constant Summary
-
LEADER_LINE_TYPE_BEZIER =
# File 'lib/sketchup-api-stubs/stubs/Layout/LinearDimension.rb', line 25
Constants
nil
-
LEADER_LINE_TYPE_HIDDEN =
# File 'lib/sketchup-api-stubs/stubs/Layout/LinearDimension.rb', line 26
Stub value.
nil
-
LEADER_LINE_TYPE_SINGLE_SEGMENT =
# File 'lib/sketchup-api-stubs/stubs/Layout/LinearDimension.rb', line 27
Stub value.
nil
-
LEADER_LINE_TYPE_TWO_SEGMENT =
# File 'lib/sketchup-api-stubs/stubs/Layout/LinearDimension.rb', line 28
Stub value.
nil
Class Method Summary
-
.new(start_point, end_point, height) ⇒ Layout::LinearDimension
constructor
The
#initialize
method creates a new disconnectedLinearDimension
.
Instance Attribute Summary
-
#auto_scale=(uses_auto_scale)
rw
The #auto_scale= method sets whether the scale for the
LinearDimension
is set automatically. -
#auto_scale? ⇒ Boolean
rw
The #auto_scale? method returns whether the scale for the
LinearDimension
is set automatically. -
#custom_text=(uses_custom_text)
rw
The #custom_text= method sets whether the
LinearDimension
uses custom text. -
#custom_text? ⇒ Boolean
rw
The #custom_text? method returns whether the
LinearDimension
uses custom text. -
#end_connection_point ⇒ Geom::Point2d
rw
The #end_connection_point method returns the paper space location for the second connection.
-
#end_connection_point=(end_point)
rw
The #end_connection_point= method sets the paper space location for the second connection.
-
#end_extent_point ⇒ Geom::Point2d
rw
The #end_extent_point method returns the paper space location for the end of the dimension line.
-
#end_extent_point=(end_extent)
rw
The #end_extent_point= method sets the paper space location for the end of the dimension line.
-
#end_offset_length=(offset_length)
writeonly
The #end_offset_length= method sets the length of the offset from the second
ConnectionPoint
to the start of the second extension line. -
#leader_line_type ⇒ Integer
rw
The #leader_line_type method returns the type of leader line the
LinearDimension
is using. -
#leader_line_type=(type)
rw
The #leader_line_type= method sets the type of leader line the
LinearDimension
is using. -
#scale ⇒ Numeric
rw
The #scale method returns the scale being used for the
LinearDimension
. -
#scale=(scale)
rw
The #scale= method sets the scale being used for the
LinearDimension
. -
#start_connection_point ⇒ Geom::Point2d
rw
The #start_connection_point method returns the paper space location for the first connection.
-
#start_connection_point=(start_point)
rw
The #start_connection_point= method sets the paper space location for the first connection.
-
#start_extent_point ⇒ Geom::Point2d
rw
The #start_extent_point method returns the paper space location for the start of the dimension line.
-
#start_extent_point=(start_extent)
rw
The #start_extent_point= method sets the paper space location for the start of the dimension line.
-
#start_offset_length=(offset_length)
writeonly
The #start_offset_length= method sets the length of the offset from the first
ConnectionPoint
to the start of the first extension line. -
#text ⇒ Layout::FormattedText
rw
The #text method returns a copy of the
LinearDimension
‘sFormattedText
. -
#text=(formatted_text)
rw
The #text= method sets the
LinearDimension
‘sFormattedText
.
Entity
- Inherited
| #locked= | The |
| #locked? | The |
| #on_shared_layer? | |
| #style | |
| #style= | |
| #untransformed_bounds | The |
| #untransformed_bounds= | The |
Instance Method Summary
-
#connect(start_connection, end_connection)
The #connect method connects the
LinearDimension
to one or twoEntity
s using the providedConnectionPoint
s. -
#disconnect
The #disconnect method disconnects the
LinearDimension
from itsConnectionPoint
s. -
#end_offset_point ⇒ Geom::Point2d
The #end_offset_point method returns the paper space location for the end of the first extension line.
- #entities ⇒ Layout::Entities
-
#start_offset_point ⇒ Geom::Point2d
The #start_offset_point method returns the paper space location for the start of the first extension line.
Entity
- Inherited
| #== | The |
| #bounds | The |
| #document | |
| #drawing_bounds | The |
| #group | |
| #layer_instance | The |
| #move_to_group | |
| #move_to_layer | |
| #page | |
| #transform! | The |
| #transformation | The |
Constructor Details
.new(start_point, end_point, height) ⇒ LinearDimension
The #initialize
method creates a new disconnected LinearDimension
.
Instance Attribute Details
#auto_scale=(uses_auto_scale) (rw)
The #auto_scale=
method sets whether the scale for the LinearDimension
is set automatically.
#auto_scale? ⇒ Boolean
(rw)
The #auto_scale?
method returns whether the scale for the LinearDimension
is set automatically.
#custom_text=(uses_custom_text) (rw)
The #custom_text=
method sets whether the LinearDimension
uses custom text. When true
, the LinearDimension
will display a custom string that doesn’t change. When false
, it will display the length measurement and will update automatically.
#custom_text? ⇒ Boolean
(rw)
The #custom_text?
method returns whether the LinearDimension
uses custom text. When true
, the LinearDimension
will display a custom string that doesn’t change. When false
, it will display the length measurement and will update automatically.
#end_connection_point ⇒ Geom::Point2d (rw)
The #end_connection_point
method returns the paper space location for the second connection.
#end_connection_point=(end_point) (rw)
The #end_connection_point=
method sets the paper space location for the second connection.
#end_extent_point ⇒ Geom::Point2d (rw)
The #end_extent_point
method returns the paper space location for the end of the dimension line.
#end_extent_point=(end_extent) (rw)
The #end_extent_point=
method sets the paper space location for the end of the dimension line.
#end_offset_length=(offset_length) (writeonly)
The #end_offset_length=
method sets the length of the offset from the second ConnectionPoint
to the start of the second extension line. The ConnectionPoint
and extent point will not move.
#leader_line_type ⇒ Integer
(rw)
The #leader_line_type
method returns the type of leader line the LinearDimension
is using.
The leader line type can be one of the following:
Layout::LinearDimension::LEADER_LINE_TYPE_SINGLE_SEGMENT
Layout::LinearDimension::LEADER_LINE_TYPE_TWO_SEGMENT
Layout::LinearDimension::LEADER_LINE_TYPE_BEZIER
Layout::LinearDimension::LEADER_LINE_TYPE_HIDDEN
#leader_line_type=(type) (rw)
The #leader_line_type=
method sets the type of leader line the LinearDimension
is using.
The leader line type can be one of the following:
Layout::LinearDimension::LEADER_LINE_TYPE_SINGLE_SEGMENT
Layout::LinearDimension::LEADER_LINE_TYPE_TWO_SEGMENT
Layout::LinearDimension::LEADER_LINE_TYPE_BEZIER
Layout::LinearDimension::LEADER_LINE_TYPE_HIDDEN
#scale ⇒ Numeric (rw)
The #scale
method returns the scale being used for the LinearDimension
.
#scale=(scale) (rw)
The #scale=
method sets the scale being used for the LinearDimension
.
#start_connection_point ⇒ Geom::Point2d (rw)
The #start_connection_point
method returns the paper space location for the first connection.
#start_connection_point=(start_point) (rw)
The #start_connection_point=
method sets the paper space location for the first connection.
#start_extent_point ⇒ Geom::Point2d (rw)
The #start_extent_point
method returns the paper space location for the start of the dimension line.
#start_extent_point=(start_extent) (rw)
The #start_extent_point=
method sets the paper space location for the start of the dimension line.
#start_offset_length=(offset_length) (writeonly)
The #start_offset_length=
method sets the length of the offset from the first ConnectionPoint
to the start of the first extension line. The ConnectionPoint
and extent point will not move.
#text ⇒ Layout::FormattedText (rw)
With the addition of auto-text in dimensions for LayOut 2019.2, the copy of the dimension text incorrectly provided the plain text when requesting the display text. This has been fixed for LayOut 2020.1.
The #text
method returns a copy of the LinearDimension
‘s FormattedText
.
#text=(formatted_text) (rw)
The #text=
method sets the LinearDimension
‘s FormattedText
.
Instance Method Details
#connect(start_connection, end_connection)
#disconnect
The #disconnect
method disconnects the LinearDimension
from its ConnectionPoint
s. The dimension will not be adjusted by disconnecting from its ConnectionPoint
s.
#end_offset_point ⇒ Geom::Point2d
The #end_offset_point
method returns the paper space location for the end of the first extension line. The first extension line runs from this offset point to the end extent point.
#entities ⇒ Layout::Entities
The #entities
method returns the Entities
that represent the LinearDimension
in its exploded form. Depending on the appearance of the LinearDimension
, this may return anywhere from four to six Entity
s: start extension line, end extension line, one or two dimension lines, dimension text, and optionally the leader line.
#start_offset_point ⇒ Geom::Point2d
The #start_offset_point
method returns the paper space location for the start of the first extension line. The first extension line runs from this offset point to the start extent point.


The Last Anecdote
Blog
Categories
Share
Search
Menu
Blog
Categories
Recent Posts
Sublime Text 3 Setup for Drupal
Get Set Go!


Lecture: Arrays
Background
Let's start with a quick exercise. Imagine you are trying to write an app that determines the average temperature over some given time period. Start with the following code snippet that defines three data points:
var temperature1 = 78
var temperature2 = 112
var temperature3 = 93
Write a bit of code that does the following:
- create a variable called
average
- calculate the average the of first 3 variables and assign
it to
average
Imagine you were given two new data points and want to include those in the average. Add two more variables (assign them arbitrary values) and calculate the average of all five.
But now, what if you wanted to calculate the average of 100 values, or 1000? Modifying your code to implement each of these changes would be a big hassle and involve a lot of copying & pasting. It feels like there should be some way, perhaps with a loop, that we could automate the repetition of this calculation, so that it could work for potentially many values. But using what we've learned so far, this is not possible.
Or what if you wanted to prompt the user for a number, and then average together that many values? Using variables in the way that we have been doing so far, there is no way to do this! You cannot declare a dynamic number of variables.
Thinking about how to implement the above situations, it's
almost like you need a loop. Remember, loops are used for
repetition: to create code that does something many many times,
or to create code that does something some number of times that
isn't specified until you get input from the user or
elsewhere. We've written loops to print things to the
console.  For this, you need an array.
What is an array?
Arrays are lists. An array is a single variable that contains a
list of values. In JavaScript, an array is a data
structure that contains an ordered collection
of elements. Unlike variables, where each value has a
unique name, with arrays, each value is numbered
starting at 0
. The number that you use to reference
specific values in the list is called the index.
Remember how variables were like labeled boxes? Imagine if we lined up a bunch of boxes next to each other, and now we can use how far they are from the "first" box (let's assume the first box is the one on the far left) as their label. An array is a numbered list of variables.
// this is an empty array
var myFirstArray = []
// this array is created with 8 elements
var anArrayWithNumbersInIt = [1, 1, 2, 3, 5, 8, 13, 21]
// this one, with 5
var anArrayWithStringsInIt = ["pizza", "bagel", "pho", "bao", "curry"]
// and so forth
var anArrayWithRandomStuff = ["generally", 100, "don't", 200, "do", 300, "this"]
You can use console.log(myArray)
to inspect the contents of an array.
Don't be afraid to log anything and everything to better understand what's going on
in your code.
To read data from an array we use square brackets [
]
to get a specific value from the list at the given
index:
var anArrayWithNumbersInIt = [ 11, 121, 1331 ];
console.log("first element: " + anArrayWithNumbersInIt[0])
console.log("second element: " + anArrayWithNumbersInIt[1])
console.log("third element: " + anArrayWithNumbersInIt[2])
console.log("21st element: " + anArrayWithNumbersInIt[20]) // what happens?
Notice that in JavaScript (like in most programming languages)
arrays are zero indexed. This means that the first item
in the array is referenced with [0]
. What then
would the index of the last item be? For example, what be would
the index of the last item in an array with 10 values?
To write data to an array, we use the same syntax but include the =
assignment operator we learned earlier.
anArrayWithNumbersInIt[0] = -1
anArrayWithNumbersInIt[1] = -2
anArrayWithNumbersInIt[2] = -3
// what do you expect the output to be below?
console.log( anArrayWithNumbersInIt );
anArrayWithNumbersInIt[20] = -21 // What happens here?
It's good to understand what happens in weird cases like the last line above, however you should almost never do that, and when you do it is often a bug.
Methods and Properties of Arrays
Arrays are an example of a more complex variable type in JavaScript, called objects. We won't go over objects too much here, but it's important to know that objects have methods and properties that can be accessed via the .
operator.
We can use methods and properties to interact with the object and get data out of the object. We will learn more about JavaScript objects in the Access Code program, for this workshop the only objects we will discuss are Arrays and Functions.
Array Properties
A property of an object has a value just like the other
variables we've discussed so far. Arrays only have one property
that we'll be working with: .length
, and it's value
is a number that tells us the number of values in the array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]
console.log("The length of fruits is " + fruits.length) // 4
// skipping letter trains because there are a lot...
var nycTrains = [ "1", "2", "3", "4", "5", "6", "7" ];
console.log("The length of nycTrains is " + nycTrains.length) // 7
Array Methods
A method of an object is some code that performs a bunch
of operations. We have already worked with some methods,
like console.log()
or Math.pow()
. (Our
company revenue calculator from
the Variables activity is
the type of calculation that could get wrapped up in a method,
and executed when we invoked the method.)
In JavaScript, you can tell an entity is a method if it comes
after an variable name with a .
and followed
immediately by ()
. For
example: fruits.pop()
var fruits = ["Banana", "Orange", "Apple", "Mango"]
console.log("The length of fruits is " + fruits.length) // 4
console.log("Fruits: " + fruits)
fruits.push("Papaya")
console.log("The length of fruits is now " + fruits.length) // 5
var aFruit = fruits.pop()
console.log( aFruit )
// What do you expect to see in this array now?
console.log( "Fruits:" + fruits )
You can find a great tutorial (including some advanced topics about Objects that we won't cover in this workshop) here at w3schools. The array reference documentation at w3schools is extremely helpful as well. Go there to look up the different methods and properties on arrays. Note the only useful property is length
, but it's a very important one!


Project Page
Football Data:
Football Project
Corel Draw:
Corel Draw
Creating a Website:
Creating a Wedsite
3D Printing:
3D Printing
Arduino Coding:
Arduino Coding


How To Play
Use the arrow keys to guide the falling blocks, spacebar and the up-arrow will rotate the block in opposite directions.
Alternatively the keys A,W,S and D can be used as arrow keys for the same purpose.
When a complete horizontal ring of 15 blocks is occupied by pieces the row will collapse and earn 100 points.
If multiple rows are cleared at a time you will earn bonus points.