簡體   English   中英

如何在Rails中關注的內部使用Attribute API?

[英]How to use the Attribute API inside a concern in a 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包含的鈎子來處理此問題,例如

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

然后

class Thing < ApplicationRecord
  include AConcern
end

您現在遇到的問題是在Module的上下文中調用了attribute ,但是該模塊無權訪問該方法(因此NoMethodError )。

當您調用include時, included掛鈎運行,並且該掛鈎在包含Object的上下文中運行(在這種情況下為Thing )。 Thing確實具有attribute方法,因此一切都按預期工作。

ActiveSupport::Concern included塊基本上與(在純紅寶石中)相同

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM