Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 我是否可以跨RoR中的所有http谓词/方法操作重用控制器操作的一部分?_Ruby On Rails_Rest_Httpverbs - Fatal编程技术网

Ruby on rails 我是否可以跨RoR中的所有http谓词/方法操作重用控制器操作的一部分?

Ruby on rails 我是否可以跨RoR中的所有http谓词/方法操作重用控制器操作的一部分?,ruby-on-rails,rest,httpverbs,Ruby On Rails,Rest,Httpverbs,想象一个资源:/users/14/notifications。它实现了几个HTTP谓词/方法:GET、GET/edit、POST、DELETE 所有4个操作共享一小部分逻辑:检索所有通知,创建一些散列以便于访问,从其他地方获取一些特定的用户访问权限以执行一些特殊的操作,等等。只需几个loc(比如7) 我如何重复使用这些7 loc来保持逻辑干燥?我听说过Rails的ANY动词,但我不知道如何使用它。也不知道如何在4个实际操作中使用其结果(几个变量) 我希望有这样的情况: def any @no

想象一个资源:
/users/14/notifications
。它实现了几个HTTP谓词/方法:GET、GET/edit、POST、DELETE

所有4个操作共享一小部分逻辑:检索所有通知,创建一些散列以便于访问,从其他地方获取一些特定的用户访问权限以执行一些特殊的操作,等等。只需几个loc(比如7)

我如何重复使用这些7 loc来保持逻辑干燥?我听说过Rails的ANY动词,但我不知道如何使用它。也不知道如何在4个实际操作中使用其结果(几个变量)

我希望有这样的情况:

def any
  @notifications = Notification.find_by etc...
  // do something here to create
  @reverse_notifications_hash = ...
  // and something else
  @super_special_access = ...
end

def show
  // Only specific logic here
  // Render using @notifications
end

def edit
  // Only specific logic here
  // Render form using @notifications,
  // @reverse_notifications_hash and
  // @super_special_access
end

def update 
  // Only specific logic here
  // Fetch something else special to not override stuff or be extra efficient
  more_special = ...
  // Do update stuff with @notifications, @super_special_access and more_special
end
正如您可能已经注意到的,我不是一个专业的Ruby/Railser。(语法甚至可能是错误的。)不过我很好奇


它在RoR中实际是如何工作的?

尝试使用before过滤器来执行公共代码。在您的示例中,您可以在过滤器:any之前将此行添加到控制器

编辑:


还将
any
的可见性更改为private或protected,这样就不能将其作为控制器操作公开。

显然是goYesss过滤器的常见方式。变量在实际操作中可用,方法是将它们命名为
@…
?是的,这些是实例变量,将在视图中可用。