Trouble using 'helper_method' and renderin

2019-09-04 19:16发布

问题:

I am using Ruby on Rails 3 and I am trying to set an helper_method that should work just for a controller (example: AccountsController) and for all views related to that, also when its views are rendered in another views not related to that controller. I take inspiration from the Railcast "Restricting Access".

In my accounts_controller.rb file I have

# Just to know, I am using a User namespace...
class Users::AccountsController < ApplicationController
  helper_method :show_authorization

  def show_authorization
    false # This returning value is just an example
  end
end

In my views/users/accounts/show.html.erb file I have

<% if show_authorization %>
  You are authorized!
<% else %>
  You are NOT authorized!
<% end %>

The above code works if I browse the URL http://<my_app_name>/users/accounts/1 but if I render the show.html.erb file as a template in another view file this way:

<%= render :template => "/users/accounts/show", :locals => { :account => @account } %>

I get the error:

NameError in Users#show 
undefined local variable or method `show_authorization' for #<#<Class:...>

Why? How can I solve that in order to make the AccountsController show_authorization method available to the show.html.erb view when that is rendered in another view related to another controller?

P.S.: Since the show_authorization is related only to the AccountsController and its views file, I would like to don't insert the related code in the 'application_controller.rb' file but keep that in the 'accounts_controller.rb'.

回答1:

The helper_method is practically almost the same as a defining method in accounts_helper.rb (technically it eval code against helper class). In order to use this helper you need to define it in a helper module and include it in controllers where show template meant to be rendered.

The actual problem is that different controller would know nothing about your accounts controller helpers until you explicitly require to include them.

Examples:

module Users::AccountsHelper
  code_here
end

class ApplicationHelper
  helper Users::AccountsHelper
end

all account helper methods will be available across application