4.6 Creating associations between models
In rails applications, we create connection between models
by using associations. Active Record has four types of associations:
| association | declaration | meaning | example |
| one-to-one | has_one |
when one item belongs exactly to one another item |
a molecule has a unique chemical formula |
| one-to-many | has_many |
when a single object belongs to many other objects |
a group alcohol has many hydrocarbons such as Butanol, Glycol, ... |
| many-to-many | has_and_belongs_to_many |
when the first object belongs to one or more of a
second object, and the second object belongs to one or many of the
first object |
for the relationship: have a Carbon atom, the group "Ethers" belongs to
the other groups like "Esters" or "Amines" and one of the formers
belongs to "Ethers" or others. |
| belongs-to | belongs_to |
when one item belongs to one or more other items |
a hydrocarbon belongs to a group such as "Ketones" |
Now, we will those associations to configure hydrocarbon.rb and
group.rg files in order to mach the relationships we want to set
between the two related classes. We will change these two files as
follows:
For hydrocarbon.rb:
class Hydrocarbon < ActiveRecord::Base
belongs_to :group
end
and for group.rb:
class Group < ActiveRecord::Base
has_many :hydrocarbons
end
We want by this one Hydrocarbon belongs to a single Group (group singular).
and one group can have multiple hydrocarbons (hydrocarbons plural).
4.7 Implementing validations
To set some new specific features in the model we can add them as
a validation. Set hydrocarbon.rb file like this:
class Hydrocarbon < ActiveRecord::Base
belongs_to :group
validates_presence_of : name
validates_presence_of : formula
validates_numericality_of :nbCarbons, :message=>"Error Message"
end
Set group.rb file like this:
class Group < ActiveRecord::Base
has_many :hydrocarbons
end
|