【问题标题】:Rails: In Rails how to use the model’s Attribute API on a tableless modelRails:在 Rails 中如何在无表模型上使用模型的属性 API
【发布时间】:2019-04-09 17:38:37
【问题描述】:

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

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

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

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

这会导致未定义

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

include ActiveRecord::Attributes

也包含在内,但这会导致与架构相关的不同错误。

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

【问题讨论】:

  • 你确定你应该能够做到吗?我的意思是,也许它甚至不支持在 ActiveRecord::Base 对象之外使用它。
  • 啊,那太可惜了,它有很多方便的功能,比如设置默认值。

标签: ruby-on-rails activerecord attributes ruby-on-rails-5 activemodel


【解决方案1】:

您需要包含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 是一个更专业的实现,它假设模型由数据库模式支持。

【讨论】:

  • 我试过这个,在原始问题中,它会导致与架构缓存有关的错误。
  • 不,您的问题中包含了ActiveRecord::Attributes。尽管您似乎将两者混淆了,但这根本不是一回事。我在 Rails 5.2.1 中对此进行了测试,它的工作原理与宣传的一样。
  • 哦,谢谢,我完全看错了,抱歉,我会试试这个谢谢。
【解决方案2】:

您可以使用attr_writer 实现相同的目的

class SomeModel
  include ActiveModel::Model
  attr_writer :foo

  def foo
    @foo || 100
  end
end

【讨论】:

  • 这实际上并没有达到相同的目标,因为 ActiveRecord::Attributes 比一般的访问器(例如类型转换)做得更多。
  • 你的意思是因为 ActiveModel::Attributes 比一般的访问器(例如类型转换)做得更多,而不是 ActiveRecord::Attributes 我猜。
猜你喜欢
  • 2019-04-28
  • 2010-11-20
  • 2013-04-15
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
相关资源
最近更新 更多