[Rails Level1] MODEL --Ex

CREATE MODEL

Define a Zombie model.

class Zombie < ActiveRecord::Base

end

 

VALIDATIONS I

Add a validation that checks for the presence of a Zombie's name

class Zombie < ActiveRecord::Base
  # insert validation here
  validates_presence_of :name
end

 

Add a validation that checks for the uniqueness of a Zombie's name

class Zombie < ActiveRecord::Base
  # insert validation here
  validates_uniqueness_of :name
end

 

Validate both the uniqueness and the presence of a Zombie's name on a single line, using the new validation syntax.

class Zombie < ActiveRecord::Base
  # insert validation here
  validates :name,
  uniqueness: true,
  presence: true
end

 

BELONGS TO

Weapon belongs to a Zombie. Create that relationship.

class Weapon < ActiveRecord::Base
  belongs_to :zombie
end

 

RELATIONSHIP FIND

Assuming the models and relationships are properly defined, find all the weapons that belong to Zombie 'Ash'.

Model: 

class Zombie < ActiveRecord::Base
  has_many :weapons
end
 
class Weapon < ActiveRecord::Base
  belongs_to :zombie
end
z = Zombie.find(1)
z.weapons

 

posted @ 2014-09-10 04:04  Zhentiw  阅读(235)  评论(0)    收藏  举报