簡體   English   中英

Rails應用程序中CRUD項目/微博的所有權

[英]CRUD Ownership of Items/Microposts in Rails App

我有一個簡單的rails應用程序,用戶可以在其中創建“項目”,但在列出所有項目的主索引頁面上,每個“項目”旁邊都有“顯示,編輯和刪除”鏈接。 我知道這是因為我使用腳手架來完成這些項目,但我想確保人們只能編輯他們創建的項目。 這個邏輯現在略高於我的頭腦,就像我之前說過的那樣,對於鐵軌來說我是全新的。

用戶控制器:

class UsersController < ApplicationController
  def show
    @user = User.find_by_username(params[:id])
  end
  def index
    @user = User.find(:all)
  end
end

主項目視圖:

<div class="well">
  <h1>All Items</h1>
    <table>
  <tr>
    <th>Title</th>
    <th>Details</th>
    <th>Inquire</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
<% @items.each do |item| %>
  <tr>
    <td><%= link_to item.title, item_path(item) %></td>
    <td><%= item.content %></td>
    <td><%= mail_to item.email, "Inquire", :cc => "michaelomchenry@gmail.com",
                 :subject => "OverFlow Inquiry Regarding " + item.title %></td>
    <td><%= link_to 'Show', item %></td>
    <td><%= link_to 'Edit', edit_item_path(item) %></td>
    <td><%= link_to 'Destroy', item, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>
  </table>

<br />
<%= link_to 'New Item', new_item_path %>
</div>

商品型號:

class Item < ActiveRecord::Base
  attr_accessible :content, :user_id, :title
  validates :content, :length => { :maximum => 140 }
  belongs_to :user
  delegate :email, to: :user
end

那里有很多東西。 首先,為了能夠根據用戶過濾項目(或操作),您需要知道當時登錄的人員,從而使用戶能夠登錄。 這可以通過例如使用Devise (Rails的授權gem)來完成。 Devise在很大程度上被使用並且記錄良好

設置Devise后,您可以檢查用戶是否已記錄(例如使用before_filter ),Devise將創建一個“current_user”變量供您使用(這在Devise教程中顯示 )。 然后,您可以使用它來過濾項目列表,例如:

editable_items = current_user.items

然后在視圖中使用editable_items。 我建議你去閱讀Devise教程,因為你正在做的是一個非常常見且記錄良好的任務。

如果可以的話,我會發表評論,但我覺得必須參考@momchenr發表的答案(回答他們自己的問題)作為所選答案的后續行動。

@momcher寫道:

我最終這樣做了:

 <% if item.email == current_user.email %> 

它工作......那可以嗎?

可能不是。 但這取決於系統的設置方式。 如果用戶可以編輯他們的電子郵件地址和/或電子郵件地址不是唯一的,他們可以通過臨時更改他們的電子郵件地址或僅注冊為新用戶來獲得對其他用戶的“項目”的編輯訪問權限。已知用戶的電子郵件地址。

即使您從未在應用程序中顯示用戶的電子郵件地址,當您將大部分身份驗證過程留在用戶提供的字段中時,也存在固有的漏洞。

根據您提供的信息,不確切知道如何在Devise中設置內容 - 我會嘗試以下方法:

根據調用時ActiveRecord的狀態,這兩個可能會慢一些

  • <% if item.user == current_user %>
  • <% if item.user.id == current_user.id %>

這個應該更快,因為你沒有從item對象獲取user對象(你只是直接從user對象的user_id方法拉)

  • <% if item.user_id == current_user.id %>

無論我在速度上的猜測是對還是錯,這通常都是比你所說的更好的解決方案。 由於用戶的ID永遠不會被他們直接控制 - 除非您的代碼中存在重大漏洞 - 他們不能輕易地像其他用戶那樣構成。

我最終這樣做了:

<% if item.email == current_user.email %>

它工作......那可以嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM