Я не полностью следую описанию (будет ли комментарий действительно принадлежать владельцу поездки?), Но немного расширяю ответ Джонни, вот пример, который ограничивает контроллер поездки:
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
Обязательно проверяйте журналы, так как вы делаете это, поскольку проверки, зависящие от ассоциации, могут вылиться во множество запросов, если вы не будете осторожны.