【问题标题】:Issue with Rails routes and modelsRails 路线和模型的问题
【发布时间】:2012-12-29 17:40:08
【问题描述】:

我有 2 个模型 - 用户模型和配置文件模型。我已将关系设置如下:

class User
  has_one :profile
end

class Profile
  belongs_to :user
end

我有一个具有 4 个操作的配置文件控制器 - 新创建编辑和更新。一旦用户注册或登录,他就会被重定向到 Profiles 控制器中的 New 操作。从这里我如何为该用户创建个人资料?具体来说,我应该在我的新动作和创建动作中拥有什么。现在新操作的路径只是profiles/new,它没有捕获用户参数。我正在尝试这样做,但失败了。

配置文件控制器

def new
    @user = User.find(params[:id])
    @profile = @user.build_profile
  end

  def create
    @profile = current_user.build_profile(params[:profile])
    if @profile.save
      redirect_to current_user
    else
      render new
    end
  end

【问题讨论】:

  • 下降情况如何?您的路线如何?
  • 它说找不到没有 id 的用户。 profile#new 的路由本质上是 localhost:3000/profiles/new。这里没有传递用户 ID。不知道我是否应该改变路线。我正在使用设计进行身份验证,因此它创建了一个用户并被重定向到配置文件#new。从这里开始我不知道该怎么办了。
  • 我想我想弄清楚是否需要在新操作中捕获用户 ID。我可以做这样的事情吗? def new @profile = current_user.build_profile

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

配置文件控制器中的new 操作不需要从参数中获取用户的id。 所以你的控制器会是这样的

def new
  @user = current_user
  @profile = @user.build_profile
end

def create
  @profile = current_user.build_profile(params[:profile])
  if @profile.save
    redirect_to current_user
  else
    render new
  end
end

实际上将用户的id 发送到new 操作可能是一个安全漏洞,因为我可以发送另一个用户的id 并为系统中的其他一些用户创建配置文件,这不应该被允许。

【讨论】:

  • 现在我做了一些研究,发现了单一嵌套资源的概念。这不是做事的首选方式吗?我将不得不使用 cancan 进行授权,但我认为这些路线现在更有意义。 /users/id/profile/new 或 /users/id/profile/edit。有什么想法吗?
  • 这肯定会更有意义,但是您会遇到同样的问题,即用户可能会发送另一个用户的 id,而您仍然必须使用 current_user 而不是从 id 获取用户参数,所以使用嵌套资源,但在profile的情况下仍然使用current_user
【解决方案2】:

您不应在新操作中使用User.find(params[:id]

就像在下面的创建操作中一样,您应该通过current_user 获得User

除了无法正确获取 User 之外,还有其他问题吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2015-10-11
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多