0

我有以下表格:用户、员工、联系人。员工和联系人 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

如果你用 6 代替 4,它仍然会带来那个记录。

谢谢您的帮助!

4

2 回答 2

2

首先,我认为您可能缺少一个=标志。

<% 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)。

于 2013-04-17T16:24:11.140 回答
0

步骤 #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]
于 2022-02-22T10:13:16.683 回答