gpt4 book ai didi

ruby-on-rails - before_filter :require_owner

转载 作者:行者123 更新时间:2023-12-03 16:15:49 27 4
gpt4 key购买 nike

我有许多资源(行程、时间表等),其操作应该仅限于资源的所有者。

您如何使用 ApplicationController 中定义的 #require_owner 方法实现代码以实现此目的?理想情况下,代码将查找所有者的继承链,因此 before_filter 将处理一个 :comment thatbelongs_to :trip thatbelongs_to :user。

class TripsController < ApplicationController
belongs_to :member
before_filter :require_owner

...

end

最佳答案

我没有完全遵循描述(评论真的属于旅行所有者吗?),但稍微扩展了 jonnii 的答案,这是一个限制旅行 Controller 的示例:

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
login_required方法(由restful_authentication 或authlogic 等身份验证插件提供或依赖)确保用户已登录并为用户提供 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

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

确保在执行此操作时检查日志,因为如果您不小心,依赖于关联的检查可能会膨胀成大量查询。

关于ruby-on-rails - before_filter :require_owner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1460650/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com