作爲新手ROR開發者,我一直在想辦法保護某些方法,以確保正確的用戶更新他們自己的內容。這是我的方法的一個例子。保護方法的好習慣
你會推薦一個更清潔的方式或更好的方式來完成這樣的任務嗎?
# Example Controller
class Owner::PropertiesController < Owner::BaseController
def index
end
etc.....
def update
@property = Property.find(params[:id])
# Check correct owner
check_owner(:owner_id => @property.owner_id)
if @property.update_attributes(params[:property])
redirect_to([:owner, @property], :notice => 'Property was successfully updated.')
else
render :action => "edit"
end
end
def destroy
@property = Property.find(params[:id])
# Check correct owner
check_owner(:owner_id => @property.owner_id)
@property.destroy
redirect_to(owner_properties_url)
end
private
def check_owner p = {}
if p[:owner_id] != session[:owner_id]
redirect_to([:owner, @property], :notice => "Property not found.")
end
end
感謝您的所有評論。我更喜歡保持乾燥,這很好。我不想因爲擁有許多寶石而混亂,所以只需使用並通過過濾器傳遞屬性就是完美的。 TY – Lee 2011-03-02 00:48:46