根据模型属性禁用路由
Disable a route based on model attribute
考虑到我有一个Project
模型,一个项目必须被批准才能编辑,status=pending
的项目不能编辑。
我曾经通过根据状态属性隐藏视图上的编辑链接来做到这一点,但这并不能阻止用户通过浏览器输入路线(例如:projects/1/edit
),怎么能我在给定的项目状态下无法访问编辑路径?
您不想创建条件路由。让控制器检查状态,仅在 status =='pending'
.
时才允许更新
def edit
@project = Project.find(params[:id])
if @project.status == 'pending'
render :head, :status=>401
else
#your edit code
end
end
请在下面添加before_action,您可以根据它来防止项目被编辑。
#projects_controller.rb
before_action :can_edit?, only: :edit
def edit
#your existing implementation goes here.
end
def can_edit?
@project = Project.where(id: params[:id]).first
if @project.status == pending
flash[alert] = "Sorry can't be edited"
redirect_to projects_path
end
end
考虑到我有一个Project
模型,一个项目必须被批准才能编辑,status=pending
的项目不能编辑。
我曾经通过根据状态属性隐藏视图上的编辑链接来做到这一点,但这并不能阻止用户通过浏览器输入路线(例如:projects/1/edit
),怎么能我在给定的项目状态下无法访问编辑路径?
您不想创建条件路由。让控制器检查状态,仅在 status =='pending'
.
def edit
@project = Project.find(params[:id])
if @project.status == 'pending'
render :head, :status=>401
else
#your edit code
end
end
请在下面添加before_action,您可以根据它来防止项目被编辑。
#projects_controller.rb
before_action :can_edit?, only: :edit
def edit
#your existing implementation goes here.
end
def can_edit?
@project = Project.where(id: params[:id]).first
if @project.status == pending
flash[alert] = "Sorry can't be edited"
redirect_to projects_path
end
end