如何正确使用rails中的装饰器?
How to use decorator in rails correctly?
我是使用装饰器的新手,我需要你的帮助来了解如何正确使用它以及我做错了什么。
book_decorator.rb
class BookDecorator < ApplicationDecorator
delegate_all
def in_users_list?(user)
if user.books.exists?
true
end
end
end
views/books/index.html.slim
- if book.in_users_list?(current_user)
- button_text = 'I've read this book'
... #depict some buttons and links
books_controller.rb
class BooksController < ApplicationController
expose(:book, attributes: :book_params, finder_parameter: :id)
expose_decorated(:book, decorator: BookDecorator)
...
我已经按照这些教程 (https://github.com/netguru/decent_decoration https://github.com/drapergem/draper#decorating-objects) 进行操作,看起来还不错,但是当我在书籍索引页面上时,它显示
undefined method `in_users_list?' for Book:0x007f6f4a0a4a18
我想它仍然不知道它应该使用装饰器中的方法,但是如何解决呢?我不明白我做错了什么,请帮助找到并解决问题!
先感谢您!
嗯,我只需要在 books_controller 中添加 expose_decorated(:books)。我认为这是因为我在索引方法中使用它,所以书籍(不仅仅是书籍)应该被装饰
我是使用装饰器的新手,我需要你的帮助来了解如何正确使用它以及我做错了什么。
book_decorator.rb
class BookDecorator < ApplicationDecorator
delegate_all
def in_users_list?(user)
if user.books.exists?
true
end
end
end
views/books/index.html.slim
- if book.in_users_list?(current_user)
- button_text = 'I've read this book'
... #depict some buttons and links
books_controller.rb
class BooksController < ApplicationController
expose(:book, attributes: :book_params, finder_parameter: :id)
expose_decorated(:book, decorator: BookDecorator)
...
我已经按照这些教程 (https://github.com/netguru/decent_decoration https://github.com/drapergem/draper#decorating-objects) 进行操作,看起来还不错,但是当我在书籍索引页面上时,它显示
undefined method `in_users_list?' for Book:0x007f6f4a0a4a18
我想它仍然不知道它应该使用装饰器中的方法,但是如何解决呢?我不明白我做错了什么,请帮助找到并解决问题! 先感谢您!
嗯,我只需要在 books_controller 中添加 expose_decorated(:books)。我认为这是因为我在索引方法中使用它,所以书籍(不仅仅是书籍)应该被装饰