名为“类型"的模型在 Rails 中 [英] Model named "Type" in Rails

查看:41
本文介绍了名为“类型"的模型在 Rails 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天.

我的名为Type"的模型有问题.错误是:

I have a problem with my Model named "Type". The error is:

undefined method `all' for ActiveRecord::AttributeMethods::Serialization::Type:Class

在验证的这个特定部分:

In this particular part of validation:

validates :type_id, presence: { message: 'selected is invalid' }, inclusion: { in: 1..Type.all.count }

可能是因为 Rails 中的保留名称冲突.但是,在我进行重构之前,Rails 是否会考虑这个名称?(如果无事可做).

Maybe it's due to reserved names conflict in Rails. But is there a way that Rails will consider this name before I proceed to refactor? (if nothing else to do).

这个名字确实是个糟糕的选择,但为时已晚.

It's really a bad choice for a name but it's too late.

附注.

当我在 rails 控制台中执行 'Type.all.count' 时,没有发生错误.

When I do 'Type.all.count' in rails console, there are no errors that occured.

推荐答案

Ruby 的不断查找导致它找到错误"的 Type 类.使用 "::Type" 会强制 ruby​​ 使用顶级 Type 常量.

Ruby's constant lookup is resulting in it finding the "wrong" Type class. Using "::Type" forces ruby to use the top level Type constant.

你应该注意这个计数只会做一次:当 rails 实例启动时.如果要添加新类型,验证将不会考虑到这一点.如果一个类型被删除了,那么它就不允许使用最后一个类型.

You should note that this count will be done once only: when the rails instance starts. If new types were to be added, the validation would not take that into account. If a type were ever deleted then it would not allow the last type to be used.

如果您有 type 关联,那么您可以这样做

If you have a type association then you could do

validates_presence_of :type

保存后会尝试从数据库中加载对应的 Type 对象,所以如果没有这样的行,保存会失败.

Upon saving it would try and load the corresponding Type object from the database, so saving would fail if there was no such row.

为了真正强有力的保证,您可以使用外键约束(外国人 gem 为此向 Rails 迁移添加了帮助程序,但您也可以手动编写 sql 语句)

For a really strong guarantee, you could use a foreign key constraint (the foreigner gem adds helpers to rails migrations for this, but you can also just write the sql statement by hand)

这篇关于名为“类型"的模型在 Rails 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆