validates_presence _of with non standard forgien key

时间:2015-11-17 14:54:00

标签: ruby-on-rails validation

我正在为我公司的另一个团队制作一个非常小的rails应用程序,他们的规范要求在几个地方使用非rails规范。我遇到的问题是使用validates_presence_of验证fkey字段的值。无论我给它什么价值,验证都会失败。这是我的设置

# migration approver_types
t.integer :query_type, index: true, null: false

# migration approval_query_types
t.integer :enum, index:true, null: false

# model approver_type
belongs_to :approval_query_type, foreign_key: 'enum'
validates_presence_of :approval_query_type

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

如果您使用的是Rails 4+,请尝试将required: true添加到belongs_to选项并删除状态验证:

belongs_to :approval_query_type, foreign_key: 'enum', required: true

答案 1 :(得分:0)

您似乎在enum中使用ApprovalQueryType字段作为主键(但索引不是唯一的,在这种情况下应该是唯一的)

默认情况下,Rails期望它为id,验证将(几乎)总是失败。 如果是这样,请尝试添加

self.primay_key = 'enum'

到第二个模型(可能是+唯一索引和自动增量)

相关问题