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

Min*_*ure 6 activerecord attributes ruby-on-rails activemodel ruby-on-rails-5

我有一个像这样的无表模型:

class SomeModel
  include ActiveModel::Model
  attribute :foo, :integer, default: 100
end
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用下面链接中的一个属性,它在普通模型中完美运行,但是我无法让它在无表模型中运行。

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

这会导致未定义

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

include ActiveRecord::Attributes
Run Code Online (Sandbox Code Playgroud)

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

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

max*_*max 8

你需要包括 ActiveModel::Attributes

class SomeModel
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :foo, :integer, default: 100
end
Run Code Online (Sandbox Code Playgroud)

出于某种原因,它没有包含在ActiveModel::Model. 这个内部 API 是从 Rails 5 中的 ActiveRecord 中提取出来的,因此您可以将它与无表模型一起使用。

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

  • 不,您在问题中包含了“ActiveRecord::Attributes”。尽管您似乎将两者混淆了,但这根本不是一回事。我在 Rails 5.2.1 中对此进行了测试,它的工作原理与宣传的一样。 (2认同)