我没有完全遵循描述(评论真的属于旅行所有者吗?),但稍微扩展一下 jonnii 的答案,这里是一个限制旅行控制器的示例:
class ApplicationController < ActionController::Base
...
protected
# relies on the presence of an instance variable named after the controller
def require_owner
object = instance_variable_get("@#{self.controller_name.singularize}")
unless current_user && object.is_owned_by?(current_user)
resond_to do |format|
format.html { render :text => "Not Allowed", :status => :forbidden }
end
end
end
end
class TripsController < ApplicationController
before_filter :login_required # using restful_authentication, for example
# only require these filters for actions that act on single resources
before_filter :get_trip, :only => [:show, :edit, :update, :destroy]
before_filter :require_owner, :only => [:show, :edit, :update, :destroy]
...
protected
def get_trip
@trip = Trip.find(params[:id])
end
end
假设模型如下所示:
class Trip < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
...
def is_owned_by?(agent)
self.owner == agent
# or, if you can safely assume the agent is always a User, you can
# avoid the additional user query:
# self.owner_id == agent.id
end
end
The login_required
方法(由restful_authentication或authlogic等auth插件提供或依赖)确保用户已登录并为用户提供current_user
方法,get_trip
设置随后检入的行程实例变量require_owner
.
只要该模型已实现is_owned_by?
方法。如果您在资源是评论时尝试检查它,那么您将处于CommentsController
:
class CommentsController < ApplicationController
before_filter :login_required # using restful_authentication, for example
before_filter :get_comment, :only => [:show, :edit, :update, :destroy]
before_filter :require_owner, :only => [:show, :edit, :update, :destroy]
...
protected
def get_comment
@comment = Comment.find(params[:id])
end
end
with a Comment
模型看起来像:
class Comment < ActiveRecord::Base
belongs_to :trip
# either
# delegate :is_owned_by?, :to => :trip
# or the long way:
def is_owned_by?(agent)
self.trip.is_owned_by?(agent)
end
end
确保在执行此操作时检查日志,因为如果您不小心,依赖于关联的检查可能会导致大量查询。