[英]Rails 5.2- Cannot access calling controller method from within respond_to block
I have this method in my application controller which renders the view template for the corresponding user type. 我的应用程序控制器中有此方法,该方法为相应的用户类型呈现视图模板。
class ApplicationController < ActionController::Base
def render_for_user
view = caller_locations.first.label
if current_user.blank?
render "#{view}_guest"
else
render "#{view}_#{current_user.role.downcase}"
end
end
end
And I call this method in the following fashion: 我以以下方式调用此方法:
Class CommentController < ActionController::Base
def show
@comment = Comment.find(params[:id])
render_for_user
end
end
Where I run into trouble, is calling this method from inside of a respond_to
block. 我遇到麻烦的地方是从
respond_to
块内部调用此方法。 Here is an example: 这是一个例子:
Class CommentController < ActionController::Base
def show
@comment = Comment.find(params[:id])
respond_to do |format|
format.js
format.html { render_for_user }
end
end
end
Since the controller method in the application controller just fetches the name of the calling method one step up, it's defeated by the respond_to block. 由于应用程序控制器中的控制器方法只是一步一步获取调用方法的名称,因此它被response_to块击败了。
My question is this: looking at the above code, is there a better, more flexible way to obtain the calling controller method? 我的问题是:查看上面的代码,是否有更好,更灵活的方法来获取调用控制器方法?
My question is this: looking at the above code, is there a better, more flexible way to obtain the calling controller method?
我的问题是:查看上面的代码,是否有更好,更灵活的方法来获取调用控制器方法?
controller_name
will return name.demodulize.sub(/Controller$/, '').underscore
which is probably want you want. controller_name
将返回name.demodulize.sub(/Controller$/, '').underscore
,这可能是您想要的。 I've never seen someone need to use caller_location. 我从未见过有人需要使用caller_location。 Similarly there's
action_name
同样,有
action_name
There's also params[:controller]
and params[:action]
还有
params[:controller]
和params[:action]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.