我有一个像这样的无表格模型:
class SomeModel
include ActiveModel::Model
attribute :foo, :integer, default: 100
end
我正在尝试使用下面链接中的属性,它在普通模型中完美运行但是我不能让它在无表格模型中工作。
https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html
这会导致未定义
我尝试添加活动记录属性:
include ActiveRecord::Attributes
但是,这也会导致与架构相关的不同错误。
如何在无表格模型中使用该属性?谢谢。
class SomeModel
include ActiveModel::Model
include ActiveModel::Attributes
attribute :foo, :integer, default: 100
end
由于某种原因,它不包括在ActiveModel::Model
。此内部API是从Rails 5中的ActiveRecord中提取出来的,因此您可以将其与无表格模型一起使用。
请注意,ActiveModel::Attributes
与ActiveRecord::Attributes
不同。 ActiveRecord::Attributes
是一个更专业的实现,它假定模型由数据库模式支持。
你可以用attr_writer
达到同样的效果
class SomeModel
include ActiveModel::Model
attr_writer :foo
def foo
@foo || 100
end
end