undefined method error draper gem

1.3k Views Asked by At

I am trying to user draper gem and looks like I set up just fine, however, when I call method inside my draper method, I get an "undefined method error" Here is what I have done so far.

gem 'draper'

bundle install

rails g decorator MyModel

in my Decorator, I have the follow code.

class TaskDecorator < Draper::Decorator
  delegate_all
  decorates :task

  def dummy

    print "Hello World"

  end
end

In my controller

  # GET /tasks/1
  # GET /tasks/1.json
  def show
    @task = TaskDecorator.find_by(:id => params[:id])
  end

My View

<%= @task.dummy %>

Run in the browser, I get the following error

undefined method `dummy' for #<Task:0x007fad7a639d48>

Any idea, what's wrong?

2

There are 2 best solutions below

0
On

You can also call decorates_finders in TaskDecorator like this:

class TaskDecorator < Draper::Decorator
  delegate_all
  decorates :task
  decorates_finders

  def dummy

    print "Hello World"

  end
end

Then you can get your decorated model by calling

Task.find(params[:id])
0
On

I solved this problem by replacing your:

TaskDecorator.find_by(:id => params[:id])

with:

Task.find(params[:id]).decorate

(EDIT: didn't have enough reputation to comment on the original question so original answer was asking if OP had found a solution. Now edited to include the solution I found. Admittedly an old post but leaving this here in case anybody else comes across the same problem.)