gpt4 book ai didi

ruby-on-rails - 可以在 PORO 中使用新的 ActiveRecord::Attributes API 吗?

转载 作者:行者123 更新时间:2023-12-04 05:40:15 24 4
gpt4 key购买 nike

我通常将 ActiveModel::Model 包含到一些 PORO 中(例如对于 FormObject::SignUp)。我读过新的 Rails 5 ActiveRecord::Attribute API,我想我可以用它来进行更简单的转换,但不是运气。

例如,给定

class FormObject::SignUp
include ActiveRecord::Model
include ActiveRecord::Attributes

attribute :birthday, :date
validates :birthday, presence: true
end

我收到了 NameError: undefined local variable or method `reload_schema_from_cache' for FormObjects::SignUp:Class当我尝试实例化它时出现异常。

预计不会单独使用?谢谢

最佳答案

rails >=5.2
这在 Rails 5.2 中现在是可能的。

As of Rails 5.2 (#30985), ActiveModel::Atrributes is now available to use in POROs (at least POROs that include ActiveModel::Model)...


  • 引用:https://github.com/rails/rails/issues/28020#issuecomment-456616836
  • 文档:https://www.rubydoc.info/gems/activemodel/ActiveModel/Attributes#attribute_names-instance_method

  • rails <5.2
    使用 gem ActiveModelAttributes 是我能找到的唯一简单方法。根据您的用例,使用该 gem 或采用不同的方法可能是有意义的。
    这是 gem : https://github.com/Azdaroth/active_model_attributes
    旁注:我收到反馈说仅链接的答案可能会消失。如果此链接消失,则此答案确实无效,因为这可能意味着该 gem 不再存在。

    关于ruby-on-rails - 可以在 PORO 中使用新的 ActiveRecord::Attributes API 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42252518/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com