在Rails中如何在无表格模型上使用模型的Attribute API

问题描述 投票:0回答:2

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

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

我正在尝试使用下面链接中的属性,它在普通模型中完美运行但是我不能让它在无表格模型中工作。

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

这会导致未定义

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

include ActiveRecord::Attributes

但是,这也会导致与架构相关的不同错误。

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

ruby-on-rails activerecord attributes ruby-on-rails-5 activemodel
2个回答
2
投票

你需要包括ActiveModel::Attributes

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

由于某种原因,它不包括在ActiveModel::Model。此内部API是从Rails 5中的ActiveRecord中提取出来的,因此您可以将其与无表格模型一起使用。

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


0
投票

你可以用attr_writer达到同样的效果

class SomeModel
  include ActiveModel::Model
  attr_writer :foo

  def foo
    @foo || 100
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.