Models Still Taste Like Chicken
- Named Scope
- Callbacks
- has_one
- Relationship Options
- Using Includes
- has_many :through
Named Scope
controller: // BAD CODE
def index
@rotting_zombies = Zombie.where(rotting: true)
end
above code is bad code. instead of writing where conditions in controller its good practice to write model based conditions in model. instead we can do like below:
controller: // GOOD CODE
def index
@rotting_zombies = Zombie.rotting.limit(5)
end
model:
scope :rotting, where(rotting: true)
scope :fresh, where("age < 20")
scope :recent, order("created_at desc")
scope :fresh, where("age < 20")
scope :recent, order("created_at desc")
Use Methos Chaining to Queries
Zombie.rotting.limit(5)
Zombie.recent.rotting
Zombie.recent.fresh.rotting