【问题标题】:Get Controller Object and Controller Strong Params in Application Controller获取应用控制器中的控制器对象和控制器强参数
【发布时间】:2017-10-27 19:55:31
【问题描述】:


大家好。
我正在我的 Rails 5 应用程序中创建一个日志进程,位于 application controller 内。我在那里创建是因为我想用before_save 属性调用许多控制器内的日志进程。该日志将保存用户在form 上对edit view template 执行的更改。问题是我无法在application controller 中获取<ObjectController:>。我已经从控制器中获得了instance variable,但我也需要ObjectController,因为我必须从控制器对象中获得strong parameters。 strong parameters 保存用户在输入字段中插入的所有数据。

这是我已经做过的:

应用程序/控制器/应用程序控制器

def log
    @controlr = instance_variable_get("@#{controller_name.singularize}") #get the edited object
    attribs = @controlr.attribute_names #get object table column names
    edited_data = controlr_params #stuck here!
    ctrlr = @controlr.attributes #retrive object data from db
    ...
    ##compare the edited_data with the actual data from db and check if something was changed
end

所以,我需要获取控制器对象来访问强参数,以便比较用户是否编辑了任何数据。我不确定这是否是最好的方法/做法。如果有更好的方法,我想知道。但我需要在大量需要数据日志的控制器中调用此过程。
谢谢你的时间,对不起任何不好的英语..

【问题讨论】:

    标签: ruby-on-rails object controller strong-parameters applicationcontroller


    【解决方案1】:

    如果params 方法不能帮助您实现目标(但值得一试),您始终可以通过在任何实例的上下文中调用 self 来访问控制器对象的当前实例方法或动作。

    要进行测试,您可以将byebug 放入任何操作中,在浏览器中使用附加参数调用该操作并在控制台中输入self。

    例如在控制器中:

    class UsersController < ApplicationController
      def show
        byebug
      end
    end
    

    在浏览器中:

    localhost:3000/?some_param=1234&another_param=testing

    里面会有很多有用的东西,比如self.instance_variables => [.... :@_request, ... :@_params]。

    request 方法还包含有关当前请求的所有信息,包括参数。

    希望这会有所帮助。

    【讨论】:

    • 感谢@Vladv 的回答。在应用程序控制器中使用“self”现在返回控制器对象 <0x000...><0x0000561955ce7b28>
    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 2013-08-17
    • 2019-09-21
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    相关资源
    最近更新 更多