Active Record Associations¶ ↑
This guide covers the association features of Active Record.
After reading this guide, you will know:
-
How to declare associations between Active Record models.
-
How to understand the various types of Active Record associations.
-
How to use the methods added to your models by creating associations.
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 = Order.where(customer_id: @customer.id) @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, dependent: :destroy 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.
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 associations:
-
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.
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
NOTE: belongs_to
associations must use the singular
term. If you used the pluralized form in the above example for the
customer
association in the Order
model, you
would be told that there was an “uninitialized constant Order::Customers”.
This is because Rails automatically infers the class name from the
association name. If the association name is wrongly pluralized, then the
inferred class will be wrongly pluralized too.
The corresponding migration might look like this:
class CreateOrders < ActiveRecord::Migration def change create_table :customers do |t| t.string :name t.timestamps null: false end create_table :orders do |t| t.belongs_to :customer, index: true t.datetime :order_date t.timestamps null: false end end end
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
The corresponding migration might look like this:
class CreateSuppliers < ActiveRecord::Migration def change create_table :suppliers do |t| t.string :name t.timestamps null: false end create_table :accounts do |t| t.belongs_to :supplier, index: true t.string :account_number t.timestamps null: false end end end
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
NOTE: The name of the other model is pluralized when declaring a
has_many
association.
The corresponding migration might look like this:
class CreateCustomers < ActiveRecord::Migration def change create_table :customers do |t| t.string :name t.timestamps null: false end create_table :orders do |t| t.belongs_to :customer, index:true t.datetime :order_date t.timestamps null: false end end end
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 corresponding migration might look like this:
class CreateAppointments < ActiveRecord::Migration def change create_table :physicians do |t| t.string :name t.timestamps null: false end create_table :patients do |t| t.string :name t.timestamps null: false end create_table :appointments do |t| t.belongs_to :physician, index: true t.belongs_to :patient, index: true t.datetime :appointment_date t.timestamps null: false end end end
The collection of join models can be managed via the API. For example, if you assign
physician.patients = patients
new join models are created for newly associated objects, and if some are gone their rows are deleted.
WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.
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
With through: :sections
specified, Rails will now understand:
@document.paragraphs
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
supplier 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
The corresponding migration might look like this:
class CreateAccountHistories < ActiveRecord::Migration def change create_table :suppliers do |t| t.string :name t.timestamps null: false end create_table :accounts do |t| t.belongs_to :supplier, index: true t.string :account_number t.timestamps null: false end create_table :account_histories do |t| t.belongs_to :account, index: true t.integer :credit_rating t.timestamps null: false end end end
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
The corresponding migration might look like this:
class CreateAssembliesAndParts < ActiveRecord::Migration def change create_table :assemblies do |t| t.string :name t.timestamps null: false end create_table :parts do |t| t.string :part_number t.timestamps null: false end create_table :assemblies_parts, id: false do |t| t.belongs_to :assembly, index: true t.belongs_to :part, index: true end end end
Choosing Between belongs_to
and has_one
¶ ↑
If you want to set up a one-to-one 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 change create_table :suppliers do |t| t.string :name t.timestamps null: false end create_table :accounts do |t| t.integer :supplier_id t.string :account_number t.timestamps null: false end add_index :accounts, :supplier_id end end
NOTE: Using t.integer :supplier_id
makes the foreign key
naming obvious and explicit. In current versions of Rails, you can abstract
away this implementation detail by using t.references
:supplier
instead.
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 in the database).
You should use has_many :through
if you need validations,
callbacks, or extra attributes on the join model.
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 change create_table :pictures do |t| t.string :name t.integer :imageable_id t.string :imageable_type t.timestamps null: false end add_index :pictures, :imageable_id end end
This migration can be simplified by using the t.references
form:
class CreatePictures < ActiveRecord::Migration def change create_table :pictures do |t| t.string :name t.references :imageable, polymorphic: true, index: true t.timestamps null: false end end end
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 between manager and subordinates. This situation can be modeled with self-joining associations:
class Employee < ActiveRecord::Base has_many :subordinates, class_name: "Employee", foreign_key: "manager_id" belongs_to :manager, class_name: "Employee" end
With this setup, you can retrieve @employee.subordinates
and
@employee.manager
.
In your migrations/schema, you will add a references column to the model itself.
class CreateEmployees < ActiveRecord::Migration def change create_table :employees do |t| t.references :manager, index: true t.timestamps null: false end end end
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
-
Bi-directional associations
Controlling Caching¶ ↑
All of the association methods are built around caching, which 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
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.
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, depending on what sort of
associations you are creating. For belongs_to
associations you
need to create foreign keys, and for has_and_belongs_to_many
associations you need to create the appropriate join table.
Creating Foreign Keys for belongs_to
Associations¶ ↑
When you declare a belongs_to
association, you need to create
foreign keys as appropriate. For example, consider this model:
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 change create_table :orders do |t| t.datetime :order_date t.string :order_number t.integer :customer_id end add_index :orders, :customer_id 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.
Creating Join Tables for has_and_belongs_to_many
Associations¶ ↑
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 creates 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.
WARNING: 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” (because the
underscore '_' is lexicographically less than 's'
in common encodings).
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 CreateAssembliesPartsJoinTable < ActiveRecord::Migration def change create_table :assemblies_parts, id: false do |t| t.integer :assembly_id t.integer :part_id end add_index :assemblies_parts, :assembly_id add_index :assemblies_parts, :part_id end end
We pass id: false
to create_table
because that
table does not represent a model. That's required for the association
to work properly. If you observe any strange behavior in a
has_and_belongs_to_many
association like mangled models IDs,
or exceptions about conflicting IDs, chances are you forgot that bit.
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 the
following 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 namespace, 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
Bi-directional Associations¶ ↑
It's normal for associations to work in two directions, requiring declaration on two different models:
class Customer < ActiveRecord::Base has_many :orders end class Order < ActiveRecord::Base belongs_to :customer end
By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync:
c = Customer.first o = c.orders.first c.first_name == o.customer.first_name # => true c.first_name = 'Manny' c.first_name == o.customer.first_name # => false
This happens because c and o.customer are two different in-memory
representations of the same data, and neither one is automatically
refreshed from changes to the other. Active Record provides the
:inverse_of
option so that you can inform it of these
relations:
class Customer < ActiveRecord::Base has_many :orders, inverse_of: :customer end class Order < ActiveRecord::Base belongs_to :customer, inverse_of: :orders end
With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:
c = Customer.first o = c.orders.first c.first_name == o.customer.first_name # => true c.first_name = 'Manny' c.first_name == o.customer.first_name # => true
There are a few limitations to inverse_of
support:
-
They do not work with
:through
associations. -
They do not work with
:polymorphic
associations. -
They do not work with
:as
associations. -
For
belongs_to
associations,has_many
inverse associations are ignored.
Every association will attempt to automatically find the inverse
association and set the :inverse_of
option heuristically
(based on the association name). Most associations with standard names will
be supported. However, associations that contain the following options will
not have their inverses set automatically:
-
:conditions
-
:through
-
:polymorphic
-
:foreign_key
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.
belongs_to
Association Reference¶ ↑
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.
Methods Added by belongs_to
¶ ↑
When you declare a belongs_to
association, the declaring class
automatically gains five methods related to the association:
-
association(force_reload = false)
-
association=(associate)
-
build_association(attributes = {})
-
create_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= build_customer create_customer create_customer!
NOTE: When initializing a new has_one
or
belongs_to
association you must use the build_
prefix to build the association, rather than the
association.build
method that would be used for
has_many
or has_and_belongs_to_many
associations.
To create one, use the create_
prefix.
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
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, the link through this object's foreign key will be set,
and, once it passes all of the validations specified on the associated
model, the associated object will be saved.
@customer = @order.create_customer(customer_number: 123, customer_name: "John Doe")
create_association!(attributes = {})
¶ ↑
Does the same as create_association
above, but raises
ActiveRecord::RecordInvalid
if the record is invalid.
Options for belongs_to
¶ ↑
While Rails uses intelligent defaults that will work well in most
situations, there may be times when you want to customize the behavior of
the belongs_to
association reference. Such customizations can
easily be accomplished by passing options and scope blocks when you create
the association. For example, this association uses two such options:
class Order < ActiveRecord::Base belongs_to :customer, dependent: :destroy, counter_cache: true end
The belongs_to
association supports these options:
-
:autosave
-
:class_name
-
:counter_cache
-
:dependent
-
:foreign_key
-
:inverse_of
-
:polymorphic
-
:touch
-
:validate
:autosave
¶ ↑
If you set the :autosave
option to true
, Rails
will save any loaded members and destroy members that are marked for
destruction whenever you save the parent object.
: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
: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
, when the object is destroyed,destroy
will be called on its associated objects. -
:delete
, when the object is destroyed, all its associated objects will be deleted directly from the database without calling theirdestroy
method.
WARNING: 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 assumes 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
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
:inverse_of
¶ ↑
The :inverse_of
option specifies the name of the
has_many
or has_one
association that is the
inverse of this association. Does not work in combination with the
:polymorphic
options.
class Customer < ActiveRecord::Base has_many :orders, inverse_of: :customer end class Order < ActiveRecord::Base belongs_to :customer, inverse_of: :orders end
:polymorphic
¶ ↑
Passing true
to the :polymorphic
option indicates
that this is a polymorphic association. Polymorphic associations were
discussed in detail <a href=“#polymorphic-associations”>earlier in
this guide</a>.
:touch
¶ ↑
If you set the :touch
option to :true
, then the
updated_at
or updated_on
timestamp on the
associated object will be set to the current time whenever this object is
saved or destroyed:
class Order < ActiveRecord::Base belongs_to :customer, touch: true end class Customer < ActiveRecord::Base has_many :orders end
In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
class Order < ActiveRecord::Base belongs_to :customer, touch: :orders_updated_at end
: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.
Scopes for belongs_to
¶ ↑
There may be times when you wish to customize the query used by
belongs_to
. Such customizations can be achieved via a scope
block. For example:
class Order < ActiveRecord::Base belongs_to :customer, -> { where active: true }, dependent: :destroy end
You can use any of the standard querying methods inside the scope block. The following ones are discussed below:
-
where
-
includes
-
readonly
-
select
where
¶ ↑
The where
method lets you specify the conditions that the
associated object must meet.
class Order < ActiveRecord::Base belongs_to :customer, -> { where active: true } end
includes
¶ ↑
You can use the includes
method 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, -> { includes :customer } end class Order < ActiveRecord::Base belongs_to :customer has_many :line_items end class Customer < ActiveRecord::Base has_many :orders end
NOTE: There's no need to use includes
for immediate
associations - that is, if you have Order belongs_to
:customer
, then the customer is eager-loaded automatically when
it's needed.
readonly
¶ ↑
If you use readonly
, then the associated object will be
read-only when retrieved via the association.
select
¶ ↑
The select
method lets you override the SQL
SELECT
clause that is used to retrieve data about the
associated object. By default, Rails retrieves all columns.
TIP: If you use the select
method on a belongs_to
association, you should also set the :foreign_key
option to
guarantee the correct results.
Do Any Associated Objects Exist?¶ ↑
You can see if any associated objects exist by using the
association.nil?
method:
if @order.customer.nil? @msg = "No customer found for this order" end
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.
has_one
Association Reference¶ ↑
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.
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)
-
build_association(attributes = {})
-
create_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= build_account create_account create_account!
NOTE: When initializing a new has_one
or
belongs_to
association you must use the build_
prefix to build the association, rather than the
association.build
method that would be used for
has_many
or has_and_belongs_to_many
associations.
To create one, use the create_
prefix.
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.
@supplier.account = @account
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, the link through its foreign key will be set, and, once it
passes all of the validations specified on the associated model, the
associated object will be saved.
@account = @supplier.create_account(terms: "Net 30")
create_association!(attributes = {})
¶ ↑
Does the same as create_association
above, but raises
ActiveRecord::RecordInvalid
if the record is invalid.
Options for has_one
¶ ↑
While Rails uses intelligent defaults that will work well in most
situations, there may be times when you want to customize the behavior of
the has_one
association reference. Such customizations can
easily be accomplished by passing options when you create the association.
For example, this association uses two such options:
class Supplier < ActiveRecord::Base has_one :account, class_name: "Billing", dependent: :nullify end
The has_one
association supports these options:
-
:as
-
:autosave
-
:class_name
-
:dependent
-
:foreign_key
-
:inverse_of
-
:primary_key
-
:source
-
:source_type
-
:through
-
:validate
:as
¶ ↑
Setting the :as
option indicates that this is a polymorphic
association. Polymorphic associations were discussed in detail earlier in this guide.
:autosave
¶ ↑
If you set the :autosave
option to true
, Rails
will save any loaded members and destroy members that are marked for
destruction whenever you save the parent object.
: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
:dependent
¶ ↑
Controls what happens to the associated object when its owner is destroyed:
-
:destroy
causes the associated object to also be destroyed -
:delete
causes the associated object to be deleted directly from the database (so callbacks will not execute) -
:nullify
causes the foreign key to be set toNULL
. Callbacks are not executed. -
:restrict_with_exception
causes an exception to be raised if there is an associated record -
:restrict_with_error
causes an error to be added to the owner if there is an associated object
It's necessary not to set or leave :nullify
option for
those associations that have NOT NULL
database constraints. If
you don't set dependent
to destroy such associations you
won't be able to change the associated object because initial
associated object foreign key will be set to unallowed NULL
value.
:foreign_key
¶ ↑
By convention, Rails assumes 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
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
:inverse_of
¶ ↑
The :inverse_of
option specifies the name of the
belongs_to
association that is the inverse of this
association. Does not work in combination with the :through
or
:as
options.
class Supplier < ActiveRecord::Base has_one :account, inverse_of: :supplier end class Account < ActiveRecord::Base belongs_to :supplier, inverse_of: :account end
:primary_key
¶ ↑
By convention, Rails assumes 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.
: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 were
discussed in detail earlier 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.
Scopes for has_one
¶ ↑
There may be times when you wish to customize the query used by
has_one
. Such customizations can be achieved via a scope
block. For example:
class Supplier < ActiveRecord::Base has_one :account, -> { where active: true } end
You can use any of the standard querying methods inside the scope block. The following ones are discussed below:
-
where
-
includes
-
readonly
-
select
where
¶ ↑
The where
method lets you specify the conditions that the
associated object must meet.
class Supplier < ActiveRecord::Base has_one :account, -> { where "confirmed = 1" } end
includes
¶ ↑
You can use the includes
method 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, -> { includes :representative } end class Account < ActiveRecord::Base belongs_to :supplier belongs_to :representative end class Representative < ActiveRecord::Base has_many :accounts end
readonly
¶ ↑
If you use the readonly
method, then the associated object
will be read-only when retrieved via the association.
select
¶ ↑
The select
method lets you override the SQL
SELECT
clause that is used to retrieve data about the
associated object. By default, Rails retrieves all columns.
Do Any Associated Objects Exist?¶ ↑
You can see if any associated objects exist by using the
association.nil?
method:
if @supplier.account.nil? @msg = "No account found for this supplier" end
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. They will
automatically when the parent object is saved.
If you want to assign an object to a has_one
association
without saving the object, use the association.build
method.
has_many
Association Reference¶ ↑
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.
Methods Added by has_many
¶ ↑
When you declare a has_many
association, the declaring class
automatically gains 16 methods related to the association:
-
collection(force_reload = false)
-
collection<<(object, ...)
-
collection.delete(object, ...)
-
collection.destroy(object, ...)
-
collection=(objects)
-
collection_singular_ids
-
collection_singular_ids=(ids)
-
collection.clear
-
collection.empty?
-
collection.size
-
collection.find(...)
-
collection.where(...)
-
collection.exists?(...)
-
collection.build(attributes = {}, ...)
-
collection.create(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.destroy(object, ...) orders=(objects) order_ids order_ids=(ids) orders.clear orders.empty? orders.size orders.find(...) orders.where(...) orders.exists?(...) orders.build(attributes = {}, ...) orders.create(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)
WARNING: Additionally, objects will be destroyed if they're associated
with dependent: :destroy
, and deleted if they're
associated with dependent: :delete_all
.
collection.destroy(object, ...)
¶ ↑
The collection.destroy
method removes one or more objects from
the collection by running destroy
on each object.
@customer.orders.destroy(@order1)
WARNING: Objects will always be removed from the database,
ignoring the :dependent
option.
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 all objects from the
collection according to the strategy specified by the
dependent
option. If no option is given, it follows the
default strategy. The default strategy for has_many :through
associations is delete_all
, and for has_many
associations is to set the foreign keys to NULL
.
@customer.orders.clear
WARNING: Objects will be delete if they're associated with
dependent: :destroy
, just like dependent:
:delete_all
.
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(1)
collection.where(...)
¶ ↑
The collection.where
method finds objects within the
collection based on the conditions supplied but the objects are loaded
lazily meaning that the database is queried only when the object(s) are
accessed.
@open_orders = @customer.orders.where(open: true) # No query yet @open_order = @open_orders.first # Now the database will be queried
collection.exists?(...)
¶ ↑
The collection.exists?
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, once it
passes all of the validations specified on the associated model, the
associated object will be saved.
@order = @customer.orders.create(order_date: Time.now, order_number: "A12345")
collection.create!(attributes = {})
¶ ↑
Does the same as collection.create
above, but raises
ActiveRecord::RecordInvalid
if the record is invalid.
Options for has_many
¶ ↑
While Rails uses intelligent defaults that will work well in most
situations, there may be times when you want to customize the behavior of
the has_many
association reference. Such customizations can
easily be accomplished by passing options when you create the association.
For example, this association uses two such options:
class Customer < ActiveRecord::Base has_many :orders, dependent: :delete_all, validate: :false end
The has_many
association supports these options:
-
:as
-
:autosave
-
:class_name
-
:dependent
-
:foreign_key
-
:inverse_of
-
:primary_key
-
:source
-
:source_type
-
:through
-
:validate
:as
¶ ↑
Setting the :as
option indicates that this is a polymorphic
association, as discussed earlier in
this guide.
:autosave
¶ ↑
If you set the :autosave
option to true
, Rails
will save any loaded members and destroy members that are marked for
destruction whenever you save the parent object.
: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
:dependent
¶ ↑
Controls what happens to the associated objects when their owner is destroyed:
-
:destroy
causes all the associated objects to also be destroyed -
:delete_all
causes all the associated objects to be deleted directly from the database (so callbacks will not execute) -
:nullify
causes the foreign keys to be set toNULL
. Callbacks are not executed. -
:restrict_with_exception
causes an exception to be raised if there are any associated records -
:restrict_with_error
causes an error to be added to the owner if there are any associated objects
:foreign_key
¶ ↑
By convention, Rails assumes 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
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
:inverse_of
¶ ↑
The :inverse_of
option specifies the name of the
belongs_to
association that is the inverse of this
association. Does not work in combination with the :through
or
:as
options.
class Customer < ActiveRecord::Base has_many :orders, inverse_of: :customer end class Order < ActiveRecord::Base belongs_to :customer, inverse_of: :orders end
:primary_key
¶ ↑
By convention, Rails assumes that the column used to hold the primary key
of the association is id
. You can override this and explicitly
specify the primary key with the :primary_key
option.
Let's say that users
table has id
as the
primary_key but it also has guid
column. And the requirement
is that todos
table should hold guid
column value
and not id
value. This can be achieved like this
class User < ActiveRecord::Base has_many :todos, primary_key: :guid end
Now if we execute @user.todos.create
then @todo
record will have user_id
value as the guid
value
of @user
.
: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.
: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.
Scopes for has_many
¶ ↑
There may be times when you wish to customize the query used by
has_many
. Such customizations can be achieved via a scope
block. For example:
class Customer < ActiveRecord::Base has_many :orders, -> { where processed: true } end
You can use any of the standard querying methods inside the scope block. The following ones are discussed below:
-
where
-
extending
-
group
-
includes
-
limit
-
offset
-
order
-
readonly
-
select
-
uniq
where
¶ ↑
The where
method lets you specify the conditions that the
associated object must meet.
class Customer < ActiveRecord::Base has_many :confirmed_orders, -> { where "confirmed = 1" }, class_name: "Order" end
You can also set conditions via a hash:
class Customer < ActiveRecord::Base has_many :confirmed_orders, -> { where confirmed: true }, class_name: "Order" end
If you use a hash-style where
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
.
extending
¶ ↑
The extending
method specifies a named module to extend the
association proxy. Association extensions are discussed in detail later in this guide.
group
¶ ↑
The group
method 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, -> { group 'orders.id' }, through: :orders end
includes
¶ ↑
You can use the includes
method 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, -> { includes :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
method lets you restrict the total number of objects
that will be fetched through an association.
class Customer < ActiveRecord::Base has_many :recent_orders, -> { order('order_date desc').limit(100) }, class_name: "Order", end
offset
¶ ↑
The offset
method lets you specify the starting offset for
fetching objects via an association. For example, -> { offset(11)
}
will skip the first 11 records.
order
¶ ↑
The order
method dictates the order in which associated
objects will be received (in the syntax used by an SQL ORDER
BY
clause).
class Customer < ActiveRecord::Base has_many :orders, -> { order "date_confirmed DESC" } end
readonly
¶ ↑
If you use the readonly
method, then the associated objects
will be read-only when retrieved via the association.
select
¶ ↑
The select
method lets you override the SQL
SELECT
clause that is used to retrieve data about the
associated objects. By default, Rails retrieves all columns.
WARNING: 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.
distinct
¶ ↑
Use the distinct
method to keep the collection free of
duplicates. This is mostly useful together with the :through
option.
class Person < ActiveRecord::Base has_many :readings has_many :articles, through: :readings end person = Person.create(name: 'John') article = Article.create(name: 'a1') person.articles << article person.articles << article person.articles.inspect # => [#<Article id: 5, name: "a1">, #<Article id: 5, name: "a1">] Reading.all.inspect # => [#<Reading id: 12, person_id: 5, article_id: 5>, #<Reading id: 13, person_id: 5, article_id: 5>]
In the above case there are two readings and person.articles
brings out both of them even though these records are pointing to the same
article.
Now let's set distinct
:
class Person has_many :readings has_many :articles, -> { distinct }, through: :readings end person = Person.create(name: 'Honda') article = Article.create(name: 'a1') person.articles << article person.articles << article person.articles.inspect # => [#<Article id: 7, name: "a1">] Reading.all.inspect # => [#<Reading id: 16, person_id: 7, article_id: 7>, #<Reading id: 17, person_id: 7, article_id: 7>]
In the above case there are still two readings. However
person.articles
shows only one article because the collection
loads only unique records.
If you want to make sure that, upon insertion, all of the records in the
persisted association are distinct (so that you can be sure that when you
inspect the association that you will never find duplicate records), you
should add a unique index on the table itself. For example, if you have a
table named person_articles
and you want to make sure all the
articles are unique, you could add the following in a migration:
add_index :person_articles, :article, unique: true
Note that checking for uniqueness using something like
include?
is subject to race conditions. Do not attempt to use
include?
to enforce distinctness in an association. For
instance, using the article example from above, the following code would be
racy because multiple users could be attempting this at the same time:
person.articles << article unless person.articles.include?(article)
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.
has_and_belongs_to_many
Association Reference¶ ↑
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.
Methods Added by has_and_belongs_to_many
¶ ↑
When you declare a has_and_belongs_to_many
association, the
declaring class automatically gains 16 methods related to the association:
-
collection(force_reload = false)
-
collection<<(object, ...)
-
collection.delete(object, ...)
-
collection.destroy(object, ...)
-
collection=(objects)
-
collection_singular_ids
-
collection_singular_ids=(ids)
-
collection.clear
-
collection.empty?
-
collection.size
-
collection.find(...)
-
collection.where(...)
-
collection.exists?(...)
-
collection.build(attributes = {})
-
collection.create(attributes = {})
-
collection.create!(attributes = {})
In all of these methods, collection
is replaced with the
symbol passed as the first argument to
has_and_belongs_to_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.destroy(object, ...) assemblies=(objects) assembly_ids assembly_ids=(ids) assemblies.clear assemblies.empty? assemblies.size assemblies.find(...) assemblies.where(...) assemblies.exists?(...) assemblies.build(attributes = {}, ...) assemblies.create(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.
WARNING: 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
NOTE: 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)
WARNING: This does not trigger callbacks on the join records.
collection.destroy(object, ...)
¶ ↑
The collection.destroy
method removes one or more objects from
the collection by running destroy
on each record in the join
table, including running callbacks. This does not destroy the objects.
@part.assemblies.destroy(@assembly1)
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.
@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 table. This does not
destroy the associated objects.
collection.empty?
¶ ↑
The collection.empty?
method returns true
if the
collection does not contain any associated objects.
<%Q if @part.assemblies.empty? %Q< 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.
@assembly = @part.assemblies.find(1)
collection.where(...)
¶ ↑
The collection.where
method finds objects within the
collection based on the conditions supplied but the objects are loaded
lazily meaning that the database is queried only when the object(s) are
accessed. It also adds the additional condition that the object must be in
the collection.
@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
collection.exists?(...)
¶ ↑
The collection.exists?
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 object will be instantiated from the passed
attributes, the link through the join table will be created, and, once it
passes all of the validations specified on the associated model, the
associated object will be saved.
@assembly = @part.assemblies.create({assembly_name: "Transmission housing"})
collection.create!(attributes = {})
¶ ↑
Does the same as collection.create
, but raises
ActiveRecord::RecordInvalid
if the record is invalid.
Options for has_and_belongs_to_many
¶ ↑
While Rails uses intelligent defaults that will work well in most
situations, there may be times when you want to customize the behavior of
the has_and_belongs_to_many
association reference. Such
customizations can easily be accomplished by passing options when you
create the association. For example, this association uses two such
options:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, -> { readonly }, autosave: true end
The has_and_belongs_to_many
association supports these
options:
-
:association_foreign_key
-
:autosave
-
:class_name
-
:foreign_key
-
:join_table
-
:validate
:association_foreign_key
¶ ↑
By convention, Rails assumes 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:
TIP: 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
:autosave
¶ ↑
If you set the :autosave
option to true
, Rails
will save any loaded members and destroy members that are marked for
destruction whenever you save the parent object.
: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
:foreign_key
¶ ↑
By convention, Rails assumes 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
: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.
: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.
Scopes for has_and_belongs_to_many
¶ ↑
There may be times when you wish to customize the query used by
has_and_belongs_to_many
. Such customizations can be achieved
via a scope block. For example:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, -> { where active: true } end
You can use any of the standard querying methods inside the scope block. The following ones are discussed below:
-
where
-
extending
-
group
-
includes
-
limit
-
offset
-
order
-
readonly
-
select
-
uniq
where
¶ ↑
The where
method lets you specify the conditions that the
associated object must meet.
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, -> { where "factory = 'Seattle'" } end
You can also set conditions via a hash:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, -> { where factory: 'Seattle' } end
If you use a hash-style where
, 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”.
extending
¶ ↑
The extending
method specifies a named module to extend the
association proxy. Association extensions are discussed in detail later in this guide.
group
¶ ↑
The group
method 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
includes
¶ ↑
You can use the includes
method to specify second-order
associations that should be eager-loaded when this association is used.
limit
¶ ↑
The limit
method 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
method lets you specify the starting offset for
fetching objects via an association. For example, if you set
offset(11)
, it will skip the first 11 records.
order
¶ ↑
The order
method dictates the order in which associated
objects will be received (in the syntax used by an SQL ORDER
BY
clause).
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, -> { order "assembly_name ASC" } end
readonly
¶ ↑
If you use the readonly
method, then the associated objects
will be read-only when retrieved via the association.
select
¶ ↑
The select
method lets you override the SQL
SELECT
clause that is used to retrieve data about the
associated objects. By default, Rails retrieves all columns.
uniq
¶ ↑
Use the uniq
method to remove duplicates from the collection.
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.
Association Callbacks¶ ↑
Normal callbacks hook into the life cycle 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 life cycle 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.
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 where("created_at > ?", 5.days.ago) end end class Customer < ActiveRecord::Base has_many :orders, -> { extending FindRecentExtension } end class Supplier < ActiveRecord::Base has_many :deliveries, -> { extending FindRecentExtension } end
Extensions can refer to the internals of the association proxy using these
three attributes of the proxy_association
accessor:
-
proxy_association.owner
returns the object that the association is a part of. -
proxy_association.reflection
returns the reflection object that describes the association. -
proxy_association.target
returns the associated object forbelongs_to
orhas_one
, or the collection of associated objects forhas_many
orhas_and_belongs_to_many
.


{% extends "base.html" %} {% load staticfiles %} {% block content %}
Importing images from Glance will create a DB entry and allow you associate an image 'type' from the Edit screen.
Openstack Glance Image details can be found here.


Producto 1
Miles de productos hay en el mercado, pero nada como una caja con gatitos.
We all need someone to lean on, per se, be careful who you lean on.
We all need someone to lean on, per se, be careful who you lean on.
We all need someone to lean on, per se, be careful who you lean on.
We all need someone to lean on, per se, be careful who you lean on.


Announcements
Board
Committees
Dues
Covenant
FAQs
Contact Info
Covenant Form
Welcome To Prairie Fields!
Where to find us.
>


nips nips2002 nips2002-132 nips2002-132-reference knowledge-graph by maker-knowledge-mining
Source: pdf
Author: David R. Martin, Charless C. Fowlkes, Jitendra Malik
Abstract: The goal of this work is to accurately detect and localize boundaries in natural scenes using local image measurements. We formulate features that respond to characteristic changes in brightness and texture associated with natural boundaries. In order to combine the information from these features in an optimal way, a classiﬁer is trained using human labeled images as ground truth. We present precision-recall curves showing that the resulting detector outperforms existing approaches.
[1] K. Bowyer, C. Kranenburg, and S. Dougherty. Edge detector evaluation using empirical ROC curves. Proc. IEEE Conf. Comput. Vision and Pattern Recognition, 1999.
[2] J. Canny. A computational approach to edge detection. IEEE Trans. Pattern Analysis and Machine Intelligence, 8:679–698, 1986.
[3] C. Chang and C. Lin. LIBSVM: a library for support vector machines, 2001. Software available at http://www.csie.ntu.edu.tw/˜cjlin/libsvm.
[4] I. Fogel and D. Sagi. Gabor ﬁlters as texture discriminator. Bio. Cybernetics, 61:103–13, 1989.
[5] D. J. Heeger and J. R. Bergen. Pyramid-based texture analysis/synthesis. In Proceedings of SIGGRAPH ’95, pages 229–238, 1995.
[6] M. I. Jordan and R. A. Jacobs. Hierarchical mixtures of experts and the EM algorithm. Neural Computation, 6:181–214, 1994.
[7] S. Konishi, A. L. Yuille, J. Coughlan, and S. C. Zhu. Fundamental bounds on edge detection: an information theoretic evaluation of different edge cues. Proc. IEEE Conf. Comput. Vision and Pattern Recognition, pages 573–579, 1999.
[8] J. Malik, S. Belongie, T. Leung, and J. Shi. Contour and texture analysis for image segmentation. Int’l. Journal of Computer Vision, 43(1):7–27, June 2001.
[9] J. Malik and P. Perona. Preattentive texture discrimination with early vision mechanisms. J. Optical Society of America, 7(2):923–32, May 1990.
[10] D. Martin, C. Fowlkes, D. Tal, and J. Malik. A database of human segmented natural images and its application to evaluating segmentation algorithms and measuring ecological statistics. In Proc. 8th Int’l. Conf. Computer Vision, volume 2, pages 416–423, July 2001.
[11] M. Meil˘ and J. Shi. Learning segmentation by random walks. In NIPS, 2001. a
[12] M.C. Morrone and D.C. Burr. Feature detection in human vision: a phase dependent energy model. Proc. R. Soc. Lond. B, 235:221–45, 1988.
[13] M. Nitzberg, D. Mumford, and T. Shiota. Filtering, Segmentation and Depth. Springer-Verlag, 1993.
[14] P. Perona and J. Malik. Detecting and localizing edges composed of steps, peaks and roofs. In Proc. Int. Conf. Computer Vision, pages 52–7, Osaka, Japan, Dec 1990.
[15] J. Puzicha, T. Hofmann, and J. Buhmann. Non-parametric similarity measures for unsupervised texture segmentation and image retrieval. In Computer Vision and Pattern Recognition, 1997.
[16] X. Ren and J. Malik. A probabilistic multi-scale model for contour completion based on image statistics. Proc. 7th Europ. Conf. Comput. Vision, 2002.
[17] C. Van Rijsbergen. Information Retrieval, 2nd ed. Dept. of Comp. Sci., Univ. of Glasgow, 1979.
[18] J. Rivest and P. Cavanagh. Localizing contours deﬁned by more than one attribute. Vision Research, 36(1):53–66, 1996.
[19] Y. Rubner and C. Tomasi. Coalescing texture descriptors. ARPA Image Understanding Workshop, 1996.
[20] R. E. Schapire and Y. Singer. Improved boosting algorithms using conﬁdence-rated predictions. Machine Learning, 37(3):297–336, 1999.
[21] Z. Tu, S. Zhu, and H. Shum. Image segmentation by data driven markov chain monte carlo. In Proc. 8th Int’l. Conf. Computer Vision, volume 2, pages 131–138, July 2001.
[22] L.R. Williams and D.W. Jacobs. Stochastic completion ﬁelds: a neural model of illusory contour shape and salience. In Proc. 5th Int. Conf. Computer Vision, pages 408–15, June 1995.


A geometry science project from Science Buddies
The earth is massive, but you don't need a massive ruler to measure its size.
Credit: George Retseck
Key concepts
Mathematics
Geometry
Circumference
Angles
Earth's equator
Introduction
If you wanted to measure the circumference of Earth, how long would your tape measure have to be? Would you need to walk the whole way around the world to find the answer? Do you think you can do it with just a meterstick in one location? Try this project to find out!
Before you begin, however, it is important to note this project will only work within about two weeks of either the spring or fall equinoxes (usually around March 20 and September 23, respectively).
Background
What is Earth’s circumference? In the age of modern technology this may seem like an easy question for scientists to answer with tools such as satellites and GPS—and it would be even easier for you to look up the answer online. It might seem like it would be impossible for you to measure the circumference of our planet using only a meterstick. The Greek mathematician Eratosthenes, however, was able to estimate Earth’s circumference more than 2,000 years ago, without the aid of any modern technology. How? He used a little knowledge about geometry!
At the time Eratosthenes was in the city of Alexandria in Egypt. He read that in a city named Syene south of Alexandria, on a particular day of the year at noon, the sun’s reflection was visible at the bottom of a deep well. This meant the sun had to be directly overhead. (Another way to think about this is that perfectly vertical objects would cast no shadow.) On that same day in Alexandria a vertical object did cast a shadow. Using geometry, he calculated the circumference of Earth based on a few things that he knew (and one he didn’t):
- He knew there are 360 degrees in a circle.
- He could measure the angle of the shadow cast by a tall object in Alexandria.
- He knew the overland distance between Alexandria and Syene. (The two cities were close enough that the distance could be measured on foot.)
- The only unknown in the equation is the circumference of Earth!
The resulting equation was:
Angle of shadow in Alexandria / 360 degrees = Distance between Alexandria and Syene / Circumference of Earth
In this project you will do this calculation yourself by measuring the angle formed by a meterstick’s shadow at your location. You will need to do the test near the fall or spring equinoxes, when the sun is directly overhead at Earth's equator. Then you can look up the distance between your city and the equator and use the same equation Eratosthenes used to calculate Earth’s circumference. How close do you think your result will be to the “real” value?
There is a geometric rule about the angles formed by a line that intersects two parallel lines. Eratosthenes assumed the sun was far enough away from our planet that its rays were effectively parallel when they arrived at Earth. This told him the angle of the shadow he measured in Alexandria was equal to the angle between Alexandria and Syene, measured at Earth’s center. If this sounds confusing, don’t worry! It is much easier to visualize with a picture. See the references in the “More to explore” section for some helpful diagrams and a more detailed explanation of the geometry involved.
Materials
- Sunny day on or near the spring or fall equinoxes (about March 20 or September 23, respectively)
- Flat, level ground that will be in direct sunlight around noon
- Meterstick
- Volunteer to help hold the meterstick while you take measurements (Or, if you are doing the test alone, you can use a bucket of sand or dirt to insert one end of the meter stick to hold it upright.)
- Stick or rock to mark the location of the shadow
- Calculator
- Protractor
- Long piece of string
- Optional: plumb bob (you can make one by tying a small weight to the end of a string) or post level to make sure the meter stick is vertical
Preparation
- Look at your local weather forecast a few days in advance and pick a day where it looks like it will be mostly sunny around noon. (You have a window of several weeks to do this project, so don’t get discouraged if it turns out to be cloudy! You can try again.)
- Look up the sunrise and sunset times for that day in your local newspaper or on a calendar, weather or astronomy Web site. You will need to calculate “solar noon,” the time exactly halfway between sunrise and sunset, which is when the sun will be directly overhead. This will probably not be exactly 12 o’clock noon.
- Go outside and set up for your materials about 10 minutes before solar noon so you have everything ready.
Procedure
- Set up your meter stick vertically, outside in a sunny spot just before solar noon.
- If you have a volunteer to help, have them hold the meterstick. Otherwise, bury one end of the meterstick in a bucket of sand or dirt so it stays upright.
- If you have a post level or plumb bob, use it to make sure the meterstick is perfectly vertical. Otherwise, do your best to eyeball it.
- At solar noon, mark the end of the meterstick's shadow on the ground with a stick or a rock.
- Draw an imaginary line between the top of the meterstick and the tip of its shadow. Your goal is to measure the angle between this line and the meterstick. Have your volunteer stretch a piece of string between the top of the meterstick and the end of its shadow.
- Use a protractor to measure the angle between the string and the meterstick in degrees. Write this angle down.
- Look up the distance between your city and the equator.
- Calculate the circumference of the Earth using this equation:
Circumference = 360 x distance between your city and the equator / angle of shadow that you measured
- What value do you get? How close is your answer to the true circumference of Earth (see “Observations and results” section)?
- Extra: Try repeating your test on different days before, on and after the equinox; or at different times before, at and after solar noon.How much does the accuracy of your answer change?
- Extra:Ask a friend or family member in a different city to try the test on the same day and compare your results. Do you get the same answer?
Observations and results
In 200 B.C. Eratosthenes estimated Earth’s circumference at about 46,250 kilometers (28,735 miles). Today we know our planet's circumference is roughly 40,000 kilometers (24,850 miles). Not bad for a more than 2,000-year-old estimate made with no modern technology! Depending on the error in your measurements—such as the exact day and time you did the test, how accurately you were able to measure the angle or length of the shadow and how accurately you measured the distance between your city and the equator—you should be able to calculate a value fairly close to 40,000 kilometers (within a few hundred or maybe a few thousand). All without leaving your own backyard!
More to explore
Calculating the Circumference of the Earth
, from Science Buddies


Need more information?
You can contact Sustainable Education Foundation by using any of the following methods.
sustainableedufoundation
@gmail.com
Our Address
12/5, Chithra Road,
Gampaha,
Sri Lanka.
You can contact Sustainable Education Foundation by using any of the following methods.
sustainableedufoundation
@gmail.com
12/5, Chithra Road,
Gampaha,
Sri Lanka.


LEAL is a task oriented and driven by people with common interest. WE perform a variety of service and humanitarian functions, bring citizen concerns to Government, advocate and monitor policies and encourage politican participation through provision of information. We are concerned with poverty alleviation and provide needy people with the equipment and skills required for agriculture, education, health care and housing.


This application allows exploration and alignment edits between two large networks. The
networks are assumed too large to be directly rendered, so only k-hop subgraphs are ever rendered.
Help
To use:
Load a dataset by using the menu in the upper left
corner. The other dataset will also be loaded in the
right-hand pane.
Begin typing a username in the search box. The
autocomplete feature will show you some suggested names
you may be looking for.
Select the username you want, and click "Explore Local Network".
Examine the network in the left-hand pane.
Manipulate the columns in the center, sorting by
various metrics, until you see the listings you
want.
Click on a name in the central listing.
Examine the network in the right-hand pane.
If you would like to save pairing between usernames,
click "Accept This Pairing".
Click on "Review Pairings" in the navbar at the top to
see the list of pairings you have saved thus far.
The available metrics are:
Self reported match. Indicates whether
the users in the left- and right-hand panes are known to
be the same user via a message duplication from one
account to the other.
LSGM. LSGM (large seeded graph
matching) is a measure of structural similarity
between two networks, focused on a particular central
node.
Username similarity. Measures the
similarity between usernames by counting the number
of additions, deletions, and changes to individual
letters are needed to transform one name into the
other.
Username substring match. Measures
the similarity between usernames by calculating the
largest substring common to both.
1-hop neighborhood size similarity.
Measures how similar the sizes are of the 1-hop
networks surrounding the two nodes.
2-hop neighborhood sizes similarity.
Just like the 1-hop measure above, but includes a
second hop going out from the central node.
2-hop neighborhood structural similarity.
Compares two 2-hop networks, taking into account not
just size but also connectivity.
To manipulate the columns, you can:
Drag the columns into a different order.
Click on columns to order the items by that value.
Drag the edges of columns to give them a different
weight.
Click on the "Combined" column header to order the
items by the combined, weighted value of all the
columns.
Intro Video
Review Pairings
Below is a list of the entity pairs that have been selected, during this session, between the two networks:


Osinbajo, Oduduwa Versity founder harp on importance of education
by Urowayino JeremiahBy Johnbosco Agbakwuru
ABUJA- VICE President Yemi Osinbajo, weekend met with with a delegation from Oduduwa University, Ile Ife, Osun State, led by the institution’s Chancellor and Founder, Dr. Rahmon Adedoyin at the Presidential Villa, Abuja.
Prof. Osinbajo at the meeting which was held behind closed doors said that the importance of education in nation building cannot be overemphasized.
READ ALSO:Kashamu, our beloved son – Ijebu monarchs(Opens in a new browser tab)
In an interview with State House correspondents after the meeting, Dr. Adedoyin said that the visit was to invite the Vice President to the university’s forthcoming convocation.
He said that the delegation had a productive discussion with Osinbajo.
According to him, “We have our convocation ceremony coming up on Nov. 27 and No. 28 and we have come to invite the vice president to grace the occasion.
“That is precisely why we are here and to pay him a courtesy visit too.
“We charted with him and it was very fruitful.’’
On the role of educationists in reshaping the society, Adedoyin said he believed that education could be used in building worthy citizens who would be impactful to society.
He said he had deployed what God endowed him with towards the growth of society as Oduduwa University had produced professors, medical doctors among others
On the role of the traditional institution in ensuring security, he said that traditional rulers knew the grassroots and should be engaged in maintaining security.
Adedoyin, who is the Maye of Yorubaland, said that the council of kings administered the nation before the advent of civilisation.
“So, I believe that the role should still continue because they are the people who know the grassroots.
“If you look at it very well from the scratch, if you take care of your child from the scratch, apart from the school that he goes; I think you have done very well.
“So, the traditional institution is playing a very vital role in this country,’’ he said


◆ __init__()
| def chip.ChipBluezMgr.BluezDbusGattService.__init__ |
( |
|
self, |
|
|
|
bluez_obj, |
|
|
|
bluez, |
|
|
|
bus, |
|
|
|
logger = None |
|
) |
| |
◆ __del__()
| def chip.ChipBluezMgr.BluezDbusGattService.__del__ |
( |
|
self | ) |
|
◆ destroy()
| def chip.ChipBluezMgr.BluezDbusGattService.destroy |
( |
|
self | ) |
|
◆ Device()
| def chip.ChipBluezMgr.BluezDbusGattService.Device |
( |
|
self | ) |
|
◆ find_characteristic()
| def chip.ChipBluezMgr.BluezDbusGattService.find_characteristic |
( |
|
self, |
|
|
|
uuid |
|
) |
| |
◆ Primary()
| def chip.ChipBluezMgr.BluezDbusGattService.Primary |
( |
|
self | ) |
|
◆ uuid()
| def chip.ChipBluezMgr.BluezDbusGattService.uuid |
( |
|
self | ) |
|
◆ bluez
| chip.ChipBluezMgr.BluezDbusGattService.bluez |
◆ bus
| chip.ChipBluezMgr.BluezDbusGattService.bus |
◆ logger
| chip.ChipBluezMgr.BluezDbusGattService.logger |
◆ object
| chip.ChipBluezMgr.BluezDbusGattService.object |
◆ path
| chip.ChipBluezMgr.BluezDbusGattService.path |
◆ service
| chip.ChipBluezMgr.BluezDbusGattService.service |
◆ service_properties
| chip.ChipBluezMgr.BluezDbusGattService.service_properties |
The documentation for this class was generated from the following file:


Woman who adopted puppy after eagle dropped it in her garden discovers it isn't a dog
After heated discussions online about what species Wandi was, the woman took the animal to be DNA tested
by Mirror.co.ukA woman who took in what she thought was a stray puppy after an eagle dropped it in her back garden has discovered the 'adorable' animal is actually a dingo.
The woman awoke in her home in Bright, northeast of Melbourne, in August to the sounds of an animal crying outside.
She thought she had found a fox or a dog on her Wandiligong bushland property.
"I woke up this morning hearing a whimpering on my bush block, l can't tell if it's a fox or a dog," she wrote on Facebook .
After heated discussions online, the woman took the pup, named 'Wandi' after where he was found, to the Alpine Animal Hospital.
Staff at the hospital sent a DNA sample off for testing to settle the matter, Yahoo News reports.
He was sent to the Australian Dingo Foundation’s sanctuary while they awaited the results.
"After weeks of anxious waiting, results from UNSW's genetics lab revealed Wandi is a 100% pure Victoria highlands dingo," the sanctuary posted on Instagram Friday.
"Wandi will become part of our breeding program, adding new genes to increase strength and diversity of our captive insurance population of pure dingoes we have at our sanctuary," they added.
The foundation said the infant sustained injuries indicating he was seized from his home by an eagle.

At the time he was found, many people in the Facebook group correctly suggested he was a fox.
"I reckon it's a fox and you've got a little problem," one person wrote.
The dingo is Australia's only native canine and is protected in national parks under the Nature Conservation Act 1992.
However in some areas of Queensland they are classified as a pest.


Fossil’s new hybrids have customizable, E ink displays
The Fossil Hybrid HR gets heart-rate tracking and up to four subdials on a screen.
by Daniel CooperFossil's hybrid watches have always pushed back against the idea that they have to look like a smart watch in any way. Some of the current models don't even have a subdial for activity tracking, so great is the desire to keep things looking analog. That's why the next generation of Fossil hybrids are such a big deal, since they come with E ink displays that can be customized to offer any and all data on hand.
Gallery: Fossil Hybrid HR | 11 Photos
The Fossil Hybrid HR has an E ink face behind a pair of analog hands and, best of all, built-in heart-rate tracking. The latter comes from a PPG sensor on the underside of the case which will display your vitals in real time on the face. And you can add up to four complications to the display, covering your step count, alternative timezones and phone notifications through to your projected commute time. It'll work well in darkness, too, since you just need to double tap the crystal to activate the backlight.
Oh, and contrary to rumors, the Fossil Hybrid HR does not use Wear OS, but Fossil's own in-house software.
The Hybrid HR will have five different case options, all of which measure 42mm, with three working with 22mm straps, and the other two suiting 18mm straps. Each one will have around two weeks' worth of battery life on a single charge, depending on your usage. And Fossil offers a number of strap options, from leather and silicone through to stainless steel, to suit your particular style.
One thing that wasn't clear from Fossil's messaging, but we want to check out, is if the backgrounds can be used for animations. That would be a neat callback to a number of Fossil watches from its history, like the JR8621 from 2006, that had cascading text in the same style as that from The Matrix. And, frankly, I'm here for it.
The Fossil Hybrid HD is available today, with prices starting at $195 and running through to $215, depending on the options you select. There's certainly something about Fossil's pitch to make a fancier looking Pebble, especially if buying a "proper" smartwatch would leave you cold.


Download Free Games Software For Windows Pc
Windows Media Player Download 2021 Latest For Windows 10 8 7
Download Windows Media Player For Windows 7 32 64 Bit In English
Windows Media Player Windows Download
Download Windows Media Player 12 0 19041 84 For Windows Filehippo Com
Download Free Windows Media Player For Windows 7 32 Or 64 Bit
Download Windows Media Player Classic 6 4 9 1 For Windows 7 Xp Vista 32bit 64bit Media Player Classic Arcade Games For Sale Microsoft Windows
Media Player Classic 64 Bit Download 2021 Latest For Windows 10 8 7
Windows Media Player 12 For Vista Skins
Windows Media Player 12 Free Download Page 2 Line 17qq Com
Windows Media Player 11 Download For Pc Free
Windows Media Player For Mac Free Download 2013 Treejack
Media Player Classic Home Cinema Free Download Windows 64 32 Bit Mpc Hc 2015 Youtube
Official Download Of Vlc Media Player The Best Open Source Player Videolan
Windows 8 Media Player Skin V 1 5 1 Beta 32 64 By Luxorus On Deviantart
Activewin Com Microsoft Windows 7 32 64 Bit Review
Local Subtitles For Wmp 64 Bit 32 Bit 1 6 1 Download Free
Vlc Media Player Download For Windows 7 64 Bit 2021 Videolan
Rmvb Player Windows 7 64 Bits Download Peatix
標準装備のwindows Media Player 12をダウンロードするには
Https Encrypted Tbn0 Gstatic Com Images Q Tbn And9gcsy M9uwn1ug4dhxkvyznde Q3vnza4is5xvgn6lym Usqp Cau
Windows 10 Tip Find Windows Media Player And Set It As Default
Windows Media Player 12 Windows 7 64 Bit
Windows Media Player Wikipedia
Windows Media Player 7 1 Pc用ダウンロード無料
Windows Media Player 12 Free Download Downloada2z Com Flight Simulator Microsoft Flight Simulator Windows
Download And Install Windows Media Center For Windows 10
2021 Ten Best Free Flv Player For Windows 10 Windows 7 And Mac
Media Player Classic Home Cinema 64 Bit Free Download And Software Reviews Cnet Download


--- layout: post authors: ["Greg Wilson"] title: "Ongoing Discussions" date: 2016-06-20 time: "05:00:00" tags: ["Community"] ---
We've been using GitHub issues to manage discussions for the last eighteen months or so. It's working pretty well: when something on the main mailing list looks like it's going to run for a while, we push the conversation over to GitHub so that people who want to go into more detail can do so without flooding other people's mailboxes.
I've being going through those discussion issues while tidying up our lessons for their next release, and found a few that are still relevant, but which never reached a resolution. If you have thoughts on any of these, please go ahead add your comments—if your ideas don't get folded into the lessons this time, they will next.


Sorry for the inconvenience but I'm performing some maintenance at the moment. If you need to you can always contact me, otherwise I will be back online shortly!
Meanwhile, visit our website
MakarenaLabs


Multigraphs seem to change what it displays as a time stamp depending on where the data point is displayed on the x axis.
The attached screen shots where obtained by just scrolling left-right and shows that the blue line timestamp changed from 16:49 to 16:52.
Any ideas why and how to fix it?
The original data can be seen at
http://whitbyeskenergy.org.uk/emoncms/vis/multigraph?mid=10&embed=1
(the date was 27/2/16)
Thanks
Mike
Re: Multigraph Timestamps Wrong
Just had a look and noticed I could actually see it move: https://www.youtube.com/watch?v=TsykJ4uXlU0
This occurs to our multigraphs aswell, which are on emoncms.org. Not sure if yours are as well, or if you are running your own server.
Re: Multigraph Timestamps Wrong
We're on our own server - check out http://whitbyeskenergy.org.uk under the Generating tab. This graph is on the "Engineering" sub-menu
You can see all the graphs realign themselves slightly but the blue one is most pronounced.
FYI all the lines EXCEPT the blue one are 5 minute data, the blue one is one minute data.
I would love to know how to fix this as we're using this particular graph to analyse a sensor glitch and I need to know the sequence things happened.
Thanks
Mike
Re: Multigraph Timestamps Wrong
Update
I've had a look at the data files and they're all timestamped to 5 minute boundaries.
(i.e. the meta files start times are all seconds=0 and minutes multiples of 5)
The attachments in my first post show "non-5-minute" time stamps
So the question is why is multigraph getting the wrong time and why does it move?
Thanks
Mike


I have a static menu and I dont want to build anything custom to drive the dropdown.
I have a simple drop down structure but my items might change based on the model.
I want a cool template to decorate my items with to different pieces of information.
I want it all! I want my items to be actionable and cool looking.