简体   繁体   中英

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. 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.

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. I've never seen someone need to use caller_location. Similarly there's action_name

There's also params[:controller] and params[:action]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM