Reputation: 1290
This is the question
I have a Event model and a User model.
An Event has one creator of class User. I used this line in Event model to associate it:
belongs_to :creator, :class_name => "User"
So I can access the creator through this line:
event.creator
My User decorator has this line:
def full_name
"#{first_name} #{last_name}"
end
So I can decorate an User object and access user.full_name
But I need to decorate an event, and use "decorates_association" to decorate the associated User. So I need to call this line:
event.creator.full_name
I have tried this:
decorates_association :creator, {with: "UserDecorator"}
decorates_association :creator, {with: "User"}
But it throws and "undefined method `full_name'" error.
How can I prevent this error?
Thank you!
Upvotes: 0
Views: 772
Reputation: 1121
In your EventDecorator class you can do something like:
class EventDecorator < Draper::Decorator
decorates_association :creator, with: UserDecorator # no quotes
delegate :full_name, to: :creator, allow_nil: true, prefix: true
end
And then your user:
class UserDecorator < Draper::Decorator
def full_name
"#{first_name} #{last_name}"
end
end
Then in say the rails console do:
ed = Event.last.decorate
ed.creator_full_name # note the underscores thanks to the delegate
# You can also do
ed.creator.full_name
In the second example, if creator is nil you will get a method not found error. In the first, because of the allow_nil option to the delegate method in the EventDecorator you won't get an error it will just return nil.
Upvotes: 1