Rails:在Rails如何在无表模型上使用模型的属性API

Rails: In Rails how to use the model’s Attribute API on a tableless model

我有一个像这样的 table-less 模型:

class SomeModel
  include ActiveModel::Model
  attribute :foo, :integer, default: 100
end

我正在尝试使用下面 link 中的属性,它在普通模型中工作得很好,但我无法在 tableless 模型中工作。

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

这会导致未定义

我试过添加活动记录属性:

include ActiveRecord::Attributes

也作为包含,但这会导致与模式相关的不同错误。

如何在 tableless 模型中使用该属性?谢谢。

您可以使用 attr_writer

实现相同的效果
class SomeModel
  include ActiveModel::Model
  attr_writer :foo

  def foo
    @foo || 100
  end
end

您需要包括 ActiveModel::Attributes

class SomeModel
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :foo, :integer, default: 100
end

由于某些原因,它未包含在 ActiveModel::Model 中。这个内部 API 是在 Rails 5 中从 ActiveRecord 中提取出来的,因此您可以将它用于 table-less 模型。

请注意 ActiveModel::AttributesActiveRecord::Attributes 不同。 ActiveRecord::Attributes 是一个更专业的实现,它假定模型由数据库模式支持。