下面的代码是一个使用枚举的多态模型的简化版本,但我正在为验证工作而苦苦挣扎。Rails枚举验证失败
模型的最后一行是问题验证。
这工作:
validates_inclusion_of :value, in: Vote.values.keys
这不起作用返回一个错误:
validates_inclusion_of :value, in: vote_options.keys
错误
ActiveRecord::RecordInvalid: Validation failed: Value is not included in the list
型号:
class Vote < ApplicationRecord
belongs_to :voteable, polymorphic: true
vote_options = {vote_no: 0, vote_yes: 1}
enum value: vote_options
validates_inclusion_of :value, in: vote_options.keys
end
更新:
class Vote < ApplicationRecord
belongs_to :voteable, polymorphic: true
VOTE_OPTIONS = HashWithIndifferentAccess.new({ vote_no: 0, vote_yes: 1 }).freeze
EMOJI_OPTIONS = HashWithIndifferentAccess.new({thumb_up: 2, thumb_down: 3, happy_face: 4, sad_face: 5}).freeze
enum value: HashWithIndifferentAccess.new.merge(VOTE_OPTIONS).merge(EMOJI_OPTIONS)
validates_inclusion_of :value, in: vote_options.keys
end
UPDATE2:
class Like < ApplicationRecord
belongs_to :likeable, polymorphic: true
VOTE_OPTIONS = { vote_no: 0, vote_yes: 1 }.freeze
EMOJI_OPTIONS = { thumb_up: 2, thumb_down: 3, happy_face: 4, sad_face: 5 }.freeze
enum value: VOTE_OPTIONS.merge(EMOJI_OPTIONS)
with_options :if => :is_meeting? do |o|
o.validates_uniqueness_of :user_id, scope: [:likeable_id, :likeable_type], message: "You have already voted on this item."
o.validates_inclusion_of :value, in: HashWithIndifferentAccess.new(VOTE_OPTIONS).keys
end
with_options :if => :is_comment? do |o|
o.validates_uniqueness_of :user_id, scope: [:likeable_id, :likeable_type], message: "You can only tag once."
o.validates_inclusion_of :value, in: HashWithIndifferentAccess.new(EMOJI_OPTIONS).keys
end
def is_meeting?
self.likeable_type == "Meeting"
end
def is_comment?
self.likeable_type == "Comment"
end
end
是我更新使用合并方法的正确方法是什么? https://apidock.com/rails/v4.2.7/ActiveSupport/HashWithIndifferentAccess/merge – Dercni
通常是的,但看到我更新的答案IMO更可读的散列声明和合并建议。另外,我不清楚为什么你需要一个枚举值,其中一些是无效的? (注意:在我的第一个示例中也修复了属性名称。) – BoraMa
我知道,使用不带值的枚举会导致问题,因为排序是隐式的,如果添加新值,则无法更改。哪些是无效的? – Dercni