【问题标题】:Can we call a Controller's method from a view (as we call from helper ideally)?我们可以从视图中调用控制器的方法吗(理想情况下我们从助手调用)?
【发布时间】:2023-03-07 18:52:01
【问题描述】:

在 Rails MVC 中,您可以从视图调用控制器的方法吗(因为方法可以从帮助程序调用)?如果是,怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    答案如下:

    class MyController < ApplicationController
      def my_method
        # Lots of stuff
      end
      helper_method :my_method
    end
    

    然后,在您看来,您可以使用&lt;%&lt;%= 准确地在ERB 中引用它:

    <% my_method %>
    

    【讨论】:

      【解决方案2】:

      没试过这个,但是调用公共方法类似于:

      @controller.public_method
      

      和私有方法:

      @controller.send("private_method", args)
      

      查看更多详情here

      【讨论】:

        【解决方案3】:

        使用helper_method :your_action_name 制作您的操作辅助方法

        class ApplicationController < ActionController::Base
          def foo
            # your foo logic
          end
          helper_method :foo
        
          def bar
            # your bar logic
          end
          helper_method :bar
        end
        

        或者您也可以使用以下方法将所有操作作为您的辅助方法:helper :all

         class ApplicationController < ActionController::Base
           helper :all
        
           def foo
            # your foo logic
           end
        
           def bar
            # your bar logic
           end
         end
        

        在这两种情况下,您都可以从所有控制器访问 foo 和 bar。

        【讨论】:

          【解决方案4】:

          您可能希望将您的方法声明为“helper_method”,或者将其移至帮助器。

          What do helper and helper_method do?

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-05-03
            • 2016-10-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-02-13
            • 1970-01-01
            • 2019-10-07
            相关资源
            最近更新 更多