在我的頭文件中,我有一個指向Materials頁面的鏈接,我不想讓任何人訪問它,所以我需要在我的視圖中設置一個條件,在我的MaterialsController中需要一個before_filter。使控制器方法可以查看,但稍有不同?
我寫的視圖一個成功的輔助方法,但在乾燥的精神,我想寫的方法只有一次在ApplicationController中使用是helper_method其提供給視圖:
的ApplicationController:
helper_method :user_is_admin_or_teacher_or_student_with_a_class
def user_is_admin_or_teacher_or_student_with_a_class
if user_signed_in? and (current_user.admin || current_user.type == "Teacher" || ((current_user.type == "Student") and current_user.groups.any?))
else redirect_to root_path, alert: "You are not authorised to view the Materials page."
end
end
這在我MaterialsController完美工作:
before_action :user_is_admin_or_teacher_or_student_with_a_class, only: [:index, :show]
它預期的效果。
移動到事物的助手一面,我把這個在我看來(_header.html.erb):
<% if user_is_admin_or_teacher_or_student_with_a_class %>
<li><%= link_to "Materials", materials_path %></li>
<% end %>
但試圖加載我的主頁在瀏覽器的時候,我得到了「此頁有一個重定向循環'瀏覽器錯誤。我假定這是在控制器方法中的redirect_to root_path命令。
我粗的解決辦法是刪除ApplicationController中的是helper_method聲明,寫的幾乎相同的方法在ApplicationHelper:
def user_is_admin_or_teacher_or_student_with_a_class?
user_signed_in? and (current_user.admin || current_user.type == "Teacher" || ((current_user.type == "Student") and current_user.groups.any?))
end
這個作品,但它不幹燥。我該如何幹起來,只寫一次該方法,並在控制器和視圖中使用它?
您可以將通用代碼放入您的模型中,然後在您的'before_action'和您的視圖中調用。 –