gpt4 book ai didi

ruby-on-rails - 在 Ruby on Rails 中避免 View 和 Controller 之间代码重复的最佳方法是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:41 24 4
gpt4 key购买 nike

我目前在我的 ApplicationController 中有代码来检查用户是否已登录以及是否具有执行给定操作所需的访问权限(测试在 before_filter 中进行)。

我需要在 View 中使用相同的功能来决定是否应该在 ListView 中显示管理链接,但是如何最好地避免在 Controller 和 View 中重复代码?

我现在选择的方式是让 user_can_edit_customers?本质上是“can_edit_customers?”的包装器?在我的用户类上:

应用程序 Controller :

class ApplicationController 

然后在我的 View 助手中做类似的事情。

这样所有功能都封装在用户模型中,但我仍然需要在我的 Controller 和助手中定义包装器,但是有没有更聪明的方法来做到这一点?

请注意,用户内容只是一个示例 - 这也适用于其他功能。

最佳答案

我会说取消包装器,直接在传递给 View 的用户对象上调用can_edit_customers?

如果你想保留它们,一个解决方案可能是使用 helper_method 在你的 Controller 中。

helper_method :current_user, :can_edit_customers?

def current_user
@current_user ||= User.find_by_id(session[:user])
end

def can_edit_customers?
@current_user.can_edit_customers?
end

这样,该方法也可以在 View 中使用。

<% if can_edit_customers? -%>...<% end -%>

关于ruby-on-rails - 在 Ruby on Rails 中避免 View 和 Controller 之间代码重复的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/377187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com