所以我想在他/她的个人资料页面中显示用户的帖子,如顶部用户详细信息,在所有帖子下方。
我知道我可以从像 http://localhost:3000/posts?category=article 这样的 url 获取参数
与
if params[:category]
@category_id = Category.find_by(title: params[:category]).id
@posts = Post.where(category_id: @category_id)
end
但是当我有一个像 http://localhost:3000/user/adem-balka 这样的 url 时,param 不起作用
那么,我如何获取用户名以找到其 ID 并使用该用户 ID 提取帖子?
谢谢大家。
最佳答案
url 中参数的名称在您的路由文件中设置。
如果您查看 config/routes.rb
中的路由,您应该能够找到与用户模型对应的行。它应该看起来像这样:
get '/users/:name', to: 'users#show'
这意味着如果您转到/users/adem-balka,params[:name] 将被设置为“adem-balka”。然后,您可以在相应的 Controller 函数中访问该参数。
关于ruby-on-rails - 从像 http ://localhost:3000/user/adem-balka with Rails 5 这样的友好 url 获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46178376/