我有几种不同的用户类型(买家、卖家、管理员)。
我希望它们都具有相同的 account_path URL,但使用不同的操作和 View 。
我正在尝试这样的事情......
class AccountsController < ApplicationController
before_filter :render_by_user, :only => [:show]
def show
# see *_show below
end
def admin_show
...
end
def buyer_show
...
end
def client_show
...
end
end
这就是我在 ApplicationController 中定义 render_by_user 的方式...
def render_by_user
action = "#{current_user.class.to_s.downcase}_#{action_name}"
if self.respond_to?(action)
instance_variable_set("@#{current_user.class.to_s.downcase}", current_user) # e.g. set @model to current_user
self.send(action)
else
flash[:error] ||= "You're not authorized to do that."
redirect_to root_path
end
end
它在 Controller 中调用正确的 *_show 方法。但仍然尝试渲染“show.html.erb”并且没有寻找我在那里名为“admin_show.html.erb”“buyer_show.html.erb”等的正确模板。
我知道我可以手动调用
render "admin_show"
在每个 Action 中,但我认为在之前的过滤器中可能有一种更清洁的方法来完成这一切。或者有没有其他人看到过一个插件或更优雅的方式来按用户类型分解操作和 View ?谢谢!
顺便说一句,我正在使用 Rails 3(以防它有所作为)。
最佳答案
根据 View 模板的不同,将部分逻辑移到 show
中可能会有所帮助。模板代替并在那里进行切换:
<% if current_user.is_a? Admin %>
<h1> Show Admin Stuff! </h1>
<% end %>
但要回答您的问题,您需要指定要呈现的模板。如果您设置 Controller 的
@action_name
,这应该可以工作。 .您可以在 render_by_user
中执行此操作方法而不是使用本地 action
多变的:def render_by_user
self.action_name = "#{current_user.class.to_s.downcase}_#{self.action_name}"
if self.respond_to?(self.action_name)
instance_variable_set("@#{current_user.class.to_s.downcase}", current_user) # e.g. set @model to current_user
self.send(self.action_name)
else
flash[:error] ||= "You're not authorized to do that."
redirect_to root_path
end
end
关于ruby-on-rails - Rails 根据用户类型呈现不同操作和 View 的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3542928/