###Models How your rails application communicates with a data store
t = Tweet.find(3)In this app/models/tweet.rb file it finds:
class Tweet < ActiveRecord::Base
endWhen we find Tweet anywhere in our rails application, it is referencing this Tweet model (models/tweet.rb), it maps the class to the table tweets
So when we write:
t = Tweet.find(3) ...it goes looking in our tweets table and creates an instance of Tweet #3 and sets it to the variable t
To prevent the case of a new tweet being created with no values (empty) we can go back to the models/tweet.rb file and do the following:
class Tweet < ActiveRecord::Base
validate_presense_of :status
endIf we go back to the command line and type:
t = Tweet.new
=> #<Tweet id: nil, status: nil, zombie: nil>
>> t.save
=> false
t.errors.messages
=> {status:["can't be blank"]}
t.errors[:status][0]
=> "can't be blank"####Other types of validity checks:
validates_presence_of :status
validates_numericality_of :fingers
validates_uniqueness_of :toothmarks
validates_confirmation_of :password
validates_acceptance_of :zombification
validates_length_of: password, minimum: 3
validates_format_of :email, with: /regex/i
validates_inclusion_of :age, in: 21..99
validates_exclusion_of :age, in: 0...21, message: "Sorry you must be over 21"or:
validates :status,
presence: true,
uniqueness: true,
numericality: true,
length: {minimum: 0, maximum: 2000 },
format: {with: /.*/ },
acceptance: true,
confirmation: true####Relationships between different models (data stores)
When we create the model app/models/zombie.rb
class Zombie < ActiveRecord::Base
has_many :tweets
endapp/models/tweet.rb
class Tweet < ActiveRecord::Base
belongs_to :zombie
end####Using Relationships
ash = Zombie.find(1)
=> #<Zombie id: 1, name: "Ash", graveyard: "Glen Haven Memorial Cemetery">
t = Tweet.create(status: "Your eyelids taste like bacon.", zombie: ash)
=> #<Tweet id: 5, status: "Your eyelids taste like bacon.", zombie_id: 1>
ash.tweets.count
=> 3
ash.tweets
=> [#<Tweet id: 1, status: "Where can I ...", zombie_id: 1>,
#<Tweet id: 4, status: "OMG, my fingers turned..." zombie_id: 1>,
#<Tweet id: 5, status: "Your eyelides taste...", zombie_id: 1>]Additionally
t = Tweet.find(5)
=> #<Tweet id: 5, status: "Your eyelids...", zombie_id: 1>
t.zombie
=> #<Zombie id: 1, name: "Ash", graveyard: "Glen Haven Memorial Cemetery">
t.zombie.name
=> "Ash"