在 Rails 中,如何将私有方法共享给嵌套控制器?

In Rails, how can I share a private method to nested controllers?

我有一个 Player 的资源,其中包含各种嵌套资源,例如:MeasurableWorkout

我有一个变量用于 Player 的 header 在他们的页面上,它有一个变量我需要设置,无论我是从 Player_Controller 还是从一个其他嵌套资源控制器。我怎样才能干涸我的代码以在某处添加该变量,这样我就不必在每个控制器中包含相同的代码......如下所示:

玩家控制器

class PlayersController < ApplicationController
   before_action :set_measurable_summary

   #...

   private
     def set_measurable_summary
       @measurable_summary = @player.measurable_summary
     end
end

锻炼控制器

class Players::WorkoutsController < ApplicationController
   before_action :set_measurable_summary

   #...

   private
     def set_measurable_summary
       @measurable_summary = @player.measurable_summary
     end
end

这可以通过 concern 轻松完成:

# app/controllers/concerns/measurable_summary.rb

module MeasurableSummary
  extend ActiveSupport::Concern

  included do
    before_action :set_measurable_summary
  end

  private

  def set_measurable_summary
    @measurable_summary = @player.measurable_summary
  end
end

然后将其包含到您的控制器中:

class PlayersController < ApplicationController
  include MeasurableSummary
  ...
end

class Players::WorkoutsController < ApplicationController
  include MeasurableSummary
  ...
end

您可以将该方法移至 ApplicationController

class ApplicationController < ActionController::Base

  private

  def set_measurable_summary
    @measurable_summary = @player.measurable_summary
  end
end

您可以使用扩展控制器获取父私有方法。请这样做:

class Players::WorkoutsController < PlayersController
end