【问题标题】:How to move some methods in a rails controller to a different class?如何将 Rails 控制器中的某些方法移动到不同的类?
【发布时间】:2015-06-23 06:23:05
【问题描述】:

除了indexshow 和 CRUD 方法之外,我还定义了一些私有方法来简化主要方法。例如update动作依赖于assign_common_variablesset_vendorupdate_product_actions三种方法。现在这使我的控制器太大了。我需要将这些方法放到一个单独的文件中。不想将所有内容都倾倒在助手中。那么,我该怎么做呢?

控制器代码在这里:https://gist.github.com/THPubs/ad5ea6d31a1c01db5142

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    您可以将这些方法保留在您的模型中,以让您的控制器瘦而模型肥

    模型.rb

    def self.assign_common_variables
    
     # your logic
    end
    
    def self.set_vendor
     # your business logic
    end
    
    
    def self.update_product_actions
    # business logic
    end
    
    
    controller.rb
    
    def your_action
    # you can call the method you wrote in your model here like below.
     @variable = @variable.assign_common_variables
    end
      def your_another_action
    # you can call the method you wrote in your model here like below.
     @vendor = Vendor.set_vendor
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 2022-12-14
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多