ruby-on-rails - 如何在 Rails 的关注点内使用属性 API?

标签 ruby-on-rails attributes ruby-on-rails-5 activesupport-concern

我有一个简单的通用模型 rails ,如下所示:

class Thing < ApplicationRecord
  attribute :foo, :integer
  include AConcern
end

它包括一个看起来像这样的基本问题......

module AConcern
  extend ActiveSupport::Concern
end

该模型还有一个名为 :foo 的属性,使用下面的属性 api:

https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html

属性与关注点相关,因此每次我想使用关注点时,我都必须在每个模型中定义属性,然后包含关注点。

如果我将属性声明放入关注点中,如下所示:

module AConcern
  extend ActiveSupport::Concern
  attribute :foo, :integer
end

我收到以下错误:

undefined method `attribute' for AConcern:Module

如何在关注点中使用属性定义,这样我就不必在包含关注点之前在每个模型中声明它?谢谢

最佳答案

您可以使用ActiveSupport::Concern包括处理这个问题的钩子(Hook),例如

module AConcern
  extend ActiveSupport::Concern
  included do 
    attribute :foo, :integer
  end
end 

然后

class Thing < ApplicationRecord
  include AConcern
end

您现在遇到的问题是attribute正在您的 Module 的上下文中被调用但该模块无权访问该方法(因此 NoMethodError )。

included当您调用 include 时, Hook 就会运行并且该钩子(Hook)在包含 Object 的上下文中运行(本例中为Thing)。 Thing确实有attribute方法,因此一切都按预期进行。

included阻止 ActiveSupport::Concern本质上与(纯 ruby )相同

module AConcern
  def self.included(base) 
    base.class_eval { attribute :foo, :integer } 
  end 
end

关于ruby-on-rails - 如何在 Rails 的关注点内使用属性 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593533/

相关文章:

javascript - 如何检测用户第一次登录和第一次加载特定页面?

ruby-on-rails - Json.jbuilder合并2个json数据并发送给一个key

mysql - 努力通过关系添加 has_many

ruby-on-rails - rails carrierwave 为 STI 生成的 url

php - 如何使用 php Soap 库向 SoapHeader 节点添加属性

ruby-on-rails - 为什么渲染 :json in view. json.erb 导致错误,想要 :partial, :template, :inline

javascript - javascript 代码中显示的 this.value 未定义消息

php - 读取由 PHP 生成的包含 @attributes 的 JSON(使用 jQuery)

ruby-on-rails - 如何向卖家提供订单详细信息 Stripe

ruby-on-rails - PASSENGER/RVM 权限被拒绝 (13)