在 Rails 4 中,初始化模型时如何引用枚举值?
我正在使用Rails 4.2。此时,这不是升级的选择。我有这个模型
class OrderItem < ApplicationRecord
…
enum type: { data: “Data”, product: “Product” }
如何通过引用枚举来初始化对象?我尝试过,
@order_item = OrderItem.new(
order_item_params.merge(
type: :product
)
)
…
@order_item.save
但这导致了错误
NoMethodError:
undefined method `safe_constantize' for :product:Symbol
I’m using Rails 4.2. It is not an option to upgrade at this time. I have this model
class OrderItem < ApplicationRecord
…
enum type: { data: “Data”, product: “Product” }
How do I initialize my object by referencing my enum? I tried this
@order_item = OrderItem.new(
order_item_params.merge(
type: :product
)
)
…
@order_item.save
But this results in the error
NoMethodError:
undefined method `safe_constantize' for :product:Symbol
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TLDR:
type
是Rails 中inheritance_column 的默认值。该列主要用于单表继承。当它存在时,ActiveRecord 将使用此列中的值作为它从数据库中获取的每一行的类。因此,给定表
animals
具有以下值:当您调用
Animal.all.map {|m| m.class}
你会得到 [Cat, Dog, Snake]
。或者至少如果这些内容确实存在的话你会的。如果您实际上没有使用 STI 并且想要使用名称
type
,您可以将您想要的任何内容分配给self.inheritance_column
。TLDR:
type
is the default for the inheritance_column in Rails. This column is mainly used for Single Table Inheritance. When it is present ActiveRecord will use the values in this column as the class for each row it fetches from the database.So given the table
animals
with these values:When you call
Animal.all.map {|m| m.class}
you will get [Cat, Dog, Snake]
. Or at least you will if those contants actually exist.If you're not actually using STI and want to use the name
type
you can just assign whatever you want toself.inheritance_column
.我猜您遇到的是 STI 冲突,而不是
enum
问题。 Rails 为单表继承 (STI) 保留type
列名称,并使用type
存储类名,但您尝试在type< 中存储符号/代码>。 ActiveRecord 尝试将
type
值转换为类,因此抱怨无法在:product
符号上调用safe_constantize
。您可以为您的列使用不同的名称,或者告诉 ActiveRecord 对 STI 使用不同的名称(大概是您从未使用过的名称):
我认为
self.inheritance_column = nil
也适用于 Rails4,我知道nil
在 Rails6 中有效,但我不确定 Rails4 是否有效。I'd guess that you're running into an STI conflict, not an
enum
issue. Rails reserves thetype
column name for Single Table Inheritance (STI) and usestype
to store the class name but you're trying to store a Symbol intype
. ActiveRecord tries to convert thetype
value to a class, hence the complaint about not being able to callsafe_constantize
on your:product
Symbol.You could use a different name for your column or tell ActiveRecord to use a different name (presumably something you'd never use) for STI:
I think
self.inheritance_column = nil
will also work in Rails4, I knownil
works in Rails6 but I'm not certain about Rails4.