【问题标题】:Devise current_user vs user_id passed in params, nested resources update action设计 current_user vs user_id 传入参数,嵌套资源更新操作
【发布时间】:2016-10-08 23:11:53
【问题描述】:

我正在使用 Devise 进行身份验证。我有两种模型,其中用户有一个个人资料,个人资料属于用户:

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy 
end 

class Profile < ActiveRecord::Base
  belongs_to :user
end

我正在使用嵌套资源,例如

resources :users do
  resource :profile
end

为了创建一个新的用户配置文件,我使用前缀 new_user_profile_path(current_user) 路由到 prifile#new

要更新用户个人资料,我执行以下操作

# e.g. users/123/profile
current_user.profile.update(profile_params) 

这感觉不对,因为我没有在个人资料 params 中使用 the user_id =&gt; 123。 我是否应该通过 user_id 来查找用户配置文件,例如

@profile = Profile.find_by(user_id: params[:user_id])
@profile.update(profile_params)

此外,用户不能编辑其他用户的个人资料。

感谢您的反馈。

【问题讨论】:

标签: ruby-on-rails devise nested-resources


【解决方案1】:

current_user.profile.update(profile_params) 是为当前用户更新配置文件的可接受方式。

这也有助于防止配置文件被其他用户编辑。如果您将用户 ID 基于从查询字符串传入的参数,这是不安全的,并且允许任何登录用户能够更新其他用户配置文件。

例如,使用 restful 路由,任何有权访问的人都可以发布到 /users/profiles/:id,即使这不是他们自己的 ID。

current_user 是 User 模型的一个实例,并且已经包含 user_id 属性。

【讨论】:

  • 这很有意义,我实际上从允许的参数中排除了 user_id。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
相关资源
最近更新 更多