[英]Vanity URL's for Model
I want to add vanity URL's to a model in my application. 我想在应用程序中的模型中添加虚荣网址。 Ideally, I'd like it to fallback to ID's if a user doesn't have a username.
理想情况下,如果用户没有用户名,我希望它回退到ID。 Here's the current solution I've built, but it isn't working.
这是我目前构建的解决方案,但无法正常工作。
User.rb User.rb
def to_param
username || id
end
User Controller 用户控制器
@user = if params.key?(:username)
User.find_by_name(params[:username])
else
User.find(params[:id])
end
Routes 路线
match "/:username" => "users#show", via: :get
Your route generates a username param regardless of whether or not it's actually a username or an ID that you pass in. Therefore, in your controller you shouldn't be trying to use params[:id]
. 无论您实际上是传入的用户名还是ID,您的路由都会生成用户名参数。因此,在控制器中,您不应尝试使用
params[:id]
。 Other than that, I can see nothing wrong with your code. 除此之外,我看不到您的代码有什么问题。
Try this:-- 尝试这个: -
get ':id', to: 'users#show', constraints: lambda { |request| User.where(:username => request.path_parameters[:id]).exists? }
User Controller 用户控制器
@user = User.find_by_username(params[:id])
unless @user
@user = User.find(params[:id])
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.