【问题标题】:What does model.create! mean when used in a Rails controller concern?model.create 是做什么的!在 Rails 控制器中使用时的意思是什么?
【发布时间】:2016-06-06 01:04:15
【问题描述】:

model.create! 表达式是什么意思:

module StandardCreateAction
  extend ActiveSupport::Concern

  def create
   model.create!(attributes)
   render text: 'SUCCESS', status: self.class::SUCCESS_STATUS
  end
end

我猜它在使用这个 mixin 的控制器中调用了同名模型?

【问题讨论】:

  • 它在“模型”返回的任何内容上调用“创建”。您需要弄清楚“模型”方法的定义位置,并查看它返回的内容。
  • 我遇到的问题是无法在我知道的其他任何地方定义模型变量。因为该类扩展了主动关注并且没有混合。所以我想这要么是轨道魔法,要么是我不知道的东西。

标签: ruby-on-rails ruby mixins activesupport activesupport-concern


【解决方案1】:

在这种情况下,modelActiveSupport::Concern 无关,后者只是常见 ruby​​ 习语的语法糖,例如:

module SomeMixin
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      def foo
      end
    end
  end

  module ClassMethods
    def bar
    end
  end
end

在这种特定情况下,model 将在包含模块或由模块扩展的类中解析为self.model。如果self.model 无法在那里解析,它会上升到类树。

我猜是这样的:

def model
  self.class_name.chomp("Controller").singularize.constantize
end

但是,在重新发明轮子之前,您可能想看看 ActionController::Responderresponders gem

【讨论】:

  • 您先生说得非常正确。我没想到要查看调用类。你甚至说模型方法最终会扼杀控制器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 2017-09-12
  • 2013-10-31
  • 2012-08-31
  • 2013-03-10
  • 1970-01-01
  • 2020-10-27
相关资源
最近更新 更多