如何通过user_id找到设计用户?

时间:2016-03-25 03:06:11

标签: ruby-on-rails devise

所以我目前正在TreeHouse tutorial注册Ruby on Rails,但随着我的跟进,我正在根据自己的喜好修改一些正在做的事情。

然而,我遇到了一个让我摸不着头脑的问题。

我想要的是获取用户user_id页面的show。本教程所做的是为deviseprofile_name创建一个新字段。

我跳过了这一步,因为我不想让我的用户被识别出来。我希望他们的"user_id" + "first_name" + "last_name"能够识别它们。在完成教程所做的工作时,他所取得的成就是他通过使用独特的profile_name为每个注册到他网站的用户创建了自定义路由。就我而言,它将是"user_id" + "first_name" + "last_name"。如果有人可以对此有所了解,并希望也指出我的资源,我可能会在这个主题上学到更多,我真的很感激。

感谢您阅读并度过美好的一天! :d

这是他们在教程中的内容。

class ProfileController < ApplicationController
    before_filter :authenticate_user!, only: [:show]

  def show
    @user = User.find_by_profile_name(params[:id])
    //@user = User.find_by_user_id(params[:id]) //my code that I thought would work
    if @user
        @statuses = @user.statuses.all
        render action: :show
    else
        render file: 'public/404', status: 404, formats: [:html]
    end
  end
end

路线文件

Rails.application.routes.draw do
  get '/:id', to: 'profile#show'

2 个答案:

答案 0 :(得分:1)

您可能需要使用斜杠来分隔您的id / first_name / last_name参数。原因是让我们说有人的标识符最终为105johnsmith - 好吧,你怎么知道他们的名字没有输入5joh,他们的姓氏是nsmith,他们的id是10而不是105?你没有。

但是,如果您想假设标识符的前几位实际上是用户的ID,那么您只需要取params[:id]extract the integer id from the string中的任何内容。

所以你的代码如下:

id = params[:id].scan(/\d+/).first
@user = User.find_by_profile_name(id)

如果您想更改:id参数的名称,可以,但不需要它才能使其正常工作。

如果你想沿着(更明智的)在参数之间加入斜杠的路径(对于像/105/john/smith或甚至/105/johnsmith这样的网址)那么你只需要改变你的路线是:

get '/:id/:first_name/:last_name', to: 'profile#show' # maps /105/john/smith
# or
get '/:id/:full_name', to: 'profile#show' # maps /105/johnsmith

然后您可以将控制器中的代码完全保持不变。

答案 1 :(得分:0)

要查找开箱即用的用户ID:

在用户显示控制器中:@user = User.find(params[:id])

在USERS SHOW.HTML.ERB中:<p><%- @user.id %><p>