我在用着 友好_id 对于我的Rails应用程序中的路线。

我想确保无法通过数字ID访问页面。

可以这样访问页面-www.myurl.com/myfriendlyidstub

该页面不应像这样访问-www.myurl.com/12345(12345是MyFriendlyIdStub的ID)

我看不到在Friendly_id的文档中做到这一点的方法。

因此,我正在考虑在控制器中添加一种方法来检查参数是否为数字

def edit
    if params[:id].is_numeric? #I need to know how to write this method
        not_found #not_found redirects to a 404
    end 
    #rest of the edit action
end

两个问题 -

如何编写“ is_numeric”方法?

这是做事的好方法吗?你能看到任何陷阱吗?

有帮助吗?

解决方案

我会用一个 before_filter 在将其粘贴到每种方法中之前。

您也可以配置路由 段约束.

其他提示

听起来您只想将用户名作为固定链接,然后在root'/'...之后

config/route.rb
...
match '/:id' => 'controller#show'
...

之后,我相信,如果您正确设置它,它应该显示为名称而不是ID。

顺便说一句,感谢您找到Friendly_id,我正开始为我的项目寻找类似的东西。

让我知道这是否有帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top