To understand what delegate
work, let’s see the following code:
%td
= link_to queue_item.video_title, queue_item.video
%td
= link_to queue_item.category_name, queue_item.category
Suppose we had some template in the view that we call from our queueitem model. We want the video_title
from it. Actually, we can just call queue_item.video.title
or queue_item.category.name
. But we can make them more friendly by use delegate
in the model.
class QueueItem < ActiveRecord::Base
belongs_to :user
belongs_to :video
delegate :category, to: :video
delegate :title, to: :video, prefix: :video
#queue_item.video_name
#...
end
class Video < ActiveRecord::Base
belongs_to :category
has_many :reviews, -> {order("created_at DESC")}
validates :title, presence: true
validates :description, presence: true
#...
end
If you read this line: delegate :title, to: :video, prefix: :video
, it tells you that you can find the title
method in the video model
, and in this model, you add the prefix video_title
, so queue_item.video_title
now is calling the video.title
take away
- Delegation is particularly useful with Active Record associations.
- Multiple delegates to the same target are allowed