【问题标题】:Rails - I want to allow a user to change only their profileRails - 我想允许用户只更改他们的个人资料
【发布时间】:2022-02-22 18:23:15
【问题描述】:

我有以下表格:用户、员工、联系人。员工和联系人 belongs_to 用户和用户 has_one 联系人或 has_one 员工。创建新联系人或员工时,我让他们的模型创建一个新用户。

我希望联系人(最终用户)能够编辑自己的联系人记录。所以,我有以下链接:

<li><%= link_to "Edit Profile", edit_contact_path(current_user.contact) %></li>

这会调出他们的记录,他们可以对其进行编辑。但是,我不希望他们能够用另一个 contacts.id 重新输入 url 并编辑他们的记录。

我尝试了以下方法,但并没有阻止它们:

<% if current_user.contact = @contact %>
 <%= render 'form' %>
<% end %>

仅供参考 - 我还允许管理员使用此代码编辑联系人记录:

<% if current_user.admin? %>
  <%= render 'form' %>
<% end %>

进一步解释 - 网址如下所示:

http://localhost:5000/contacts/4/edit

如果将 4 替换为 6,它仍然会显示该记录。

感谢您的帮助!

【问题讨论】:

  • 我真的希望你的意思是if current_user.contact == @contact,是比较,而不是赋值。
  • 您可以使用before_filter 和自定义验证方法,该方法在任何联系人编辑页面之前被调用。这样,如果用户尝试更改 url,仍然会调用自定义验证方法。在自定义方法中,您可以检查是否为current_user == @contact。如果是,则显示编辑表单,否则重定向并显示错误消息。

标签: ruby-on-rails


【解决方案1】:

首先,我认为您可能缺少= 符号。

<% if current_user.contact == @contact %>
 <%= render 'form' %>
<% end %>

其次,在contacts#edit 上执行类似操作

if current_user.contact != @contact
  flash[:error] = "you've been naughty"
 # also its recommended to record such an abuse attempt by logging or something
else
 # do rest here
end

您还可以使用 cancan 或其他授权 gem 之类的东西做更多事情(例如,如果您希望只允许特定用户编辑联系人,而不仅仅是 current_user)。

【讨论】:

    【解决方案2】:

    步骤 #1 创建方法

    def check_contact
    if current_user.id != @contact.id
    redirect_to root_path, alert: "Opps! you're not authorized to edit this "
    end
    end
    

    步骤 #2 在控制器顶部创建一个回调

    before_action :check_contact, only: [:edit, :update]
    

    方法#2 您可能会在 check_contact 方法中进行一些更改,例如

     def check_contact
    if current_user.contact != @contact
    redirect_to root_path, alert: "Opps! you're not authorized to edit this "
    end
    end
    

    然后在控制器名称下的控制器顶部回调

    before_action :check_contact, only: [:edit, :update]
    

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 2023-04-10
      • 2020-11-04
      • 2016-01-13
      相关资源
      最近更新 更多