[Rails Level1] MODEL & Validations

1. Model in Rails:

The reason that you use Tweet then you can find the table tweets is because:

There is a class call Tweet which extends Activerecord::Base defined by Rails,

the class maps the table tweets.

 

Validations:

can add validations to check the value which will be inserted into the database.

class Tweet < ActiveRecord::Base
    validates_presenece_of :status
end

validates_presence_of will check whether the variable :status has actual value or not.

If it hasnot value, when save: it will return false

t = Tweet.new
t.save
--> false

The error message:

t.errors.messages
=> {status: ["can't be blank"]}

t.error[:status][0]
=> "can't be blank"

 

Validations api:

Read More: http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of

validates_presence_of :status                 //cannot be blank
validates_numericality_of :fingers           //should be a number
validates_uniqueness_of :toothmarks      //should be uniquene
validates_confirmation_of :password       //for passwrod, email..
validates_acceptance_of :zombification   // checkbox
validates_length_of : password, minimum: 3   //longer than 3 charaters
validates_format_of :email, width: /regex/i     //regex format
validates_inclusion_of :age, in: 21..99            //the range inside
validates_exclusion_of :age, in: 0...21, message: "sorry you much be over 21"

Also, it can write in a short way:

 

Relationship:

Read More: http://apidock.com/rails/v4.0.2/ActiveRecord/Associations/ClassMethods/belongs_to

 

  • has_many

a Zombie has_many Tweets

class Zombie < ActiveRecord::Base
    has_many :tweets
end

  • belongs_to

a Tweet belongs_to a Zombie

class Tweet < ActiveRecord::Base
    belongs_to :ombie
end

 

Using relationships:

Now we have 

  1. A zombie has many tweets.

  2. A tweet belongs to a zombie.

So if we want to find how many tweets a zombie has, then we can use:

//1. find the zmobie
ash = Zombie.find(1)

ash.tweets.count
--> 3

//2. list all the tweets
ash.tweets
    --> [id:1 ....
          id:4 ....
          id:5 ....]

 

Find the tweet belongs to which zombie:

//1. find the tweet
t = Tweet.find(5)

//2. find the zombie
t.zombie

//3. get the name
t.zombie.name

 

posted @ 2014-09-11 05:28  Zhentiw  阅读(250)  评论(0)    收藏  举报