Cannot use decorator methods in layout
Closed this issue · 4 comments
I executed rails g scaffold Post title:string body:text
.
And add following code.
- post_decorator.rb
module PostDecorator
def sample
"sample"
end
end
- application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>SampleApp</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<%= Post.first.sample %>
</head>
<body>
<%= yield %>
</body>
</html>
I got following error.
$ ./bin/rake test
Running via Spring preloader in process 1153
Loaded suite rake
Started
..E
================================================================================
Error: test: should get edit(PostsControllerTest): ActionView::Template::Error: undefined method `sample' for #<Post:0x00000005550320>
/home/kenji/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activemodel-4.2.5/lib/active_model/attribute_methods.rb:433:in `method_missing'
/home/kenji/Data/ruby/sample-app/app/views/layouts/application.html.erb:8:in `_app_views_layouts_application_html_erb__3560731179302627099_42502300'
/home/kenji/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionview-4.2.5/lib/action_view/template.rb:145:in `block in render'
/home/kenji/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.5/lib/active_support/notifications.rb:164:in `block in instrument'
... too long backtrace
.
Finished in 1.080862742 seconds.
--------------------------------------------------------------------------------
8 tests, 9 assertions, 0 failures, 4 errors, 0 pendings, 0 omissions, 0 notifications
50% passed
--------------------------------------------------------------------------------
7.40 tests/s, 8.33 assertions/s
I want to use decorator methods in layout, but I couldn't.
I moved decorator methods to helper methods and use helper methods in layout.
Thanks.
In fact, I use helper method like following instead of Post.first.sample
:
def current_site
@current_site ||= Site.find(params[:site_id])
end
Post.first.sample
This should be assigned to instance variable at controller's action.
Because of:
passing a model or collection of models or an instance of ActiveRecord::Relation from controllers to views
see: https://github.com/amatsuda/active_decorator#features
If you want to use current_xxx
helper, would you try to call it in controller?
For example before_action
or something.
Thanks! I will try it later.
Closing. Feel free to reopen if there still is any issue.