【发布时间】:2017-05-08 05:00:46
【问题描述】:
下面的代码是使用枚举的多态模型的简化版本,但我正在努力验证。
模型的最后一行是问题验证。
这行得通:
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
更新2:
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
【问题讨论】:
标签: ruby-on-rails validation enums