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)
作为一个包含但是这会导致与模式相关的不同错误。
如何在无表模型中使用该属性?谢谢。
你需要包括 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::Attributes。ActiveRecord::Attributes是一种更专业的实现,它假设模型由数据库模式支持。