Commit e6c21f24 by ivan Lan

Fix spec uniq validation & Add query_spec_with_product to Series

parent 7f274e4c
...@@ -22,10 +22,19 @@ module Shotengai ...@@ -22,10 +22,19 @@ module Shotengai
class Series < ActiveRecord::Base class Series < ActiveRecord::Base
self.table_name = 'shotengai_series' self.table_name = 'shotengai_series'
validate :check_spec, if: :spec validates_presence_of :spec
validates_uniqueness_of :spec, scope: :shotengai_product_id validate :check_spec_value
# Using validates_uniqueness_of do not work if the order of Hash is diff
validate :uniq_spec
delegate :title, :detail, :banners, :cover_image, to: :product
delegate :detail, :banners, :cover_image, to: :product scope :query_spec_with_product, ->(val, product) {
return none unless val.keys.sort == product.spec.keys.sort
keys = []; values = []
val.map { |k, v| keys << "spec->'$.\"#{k}\"' = ? "; values << v }
where(keys.join(' and '), *values)
}
class << self class << self
def inherited subclass def inherited subclass
...@@ -46,13 +55,18 @@ module Shotengai ...@@ -46,13 +55,18 @@ module Shotengai
private private
# spec 字段 # spec 字段
def check_spec def check_spec_value
raise Shotengai::WebError.new('spec 必须是个 Hash', '-1', 400) unless spec.is_a?(Hash) errors.add(:spec, 'spec 必须是个 Hash') unless spec.is_a?(Hash)
raise Shotengai::WebError.new('非法的关键字,或关键字缺失', '-1', 400) unless (product.spec.keys - spec.keys).empty? errors.add(:spec, '非法的关键字,或关键字缺失') unless (product.spec.keys - spec.keys).empty?
illegal_values = {} illegal_values = {}
spec.each { |key, value| illegal_values[key] = value unless value.in?(product.spec[key]) } spec.each { |key, value| illegal_values[key] = value unless value.in?(product.spec[key]) }
# p Shotengai::WebError.new("非法的值,#{illegal_values}", '-1', 422) errors.add(:spec, "非法的值,#{illegal_values}") unless illegal_values.empty?
raise Shotengai::WebError.new("非法的值,#{illegal_values}", '-1', 400) unless illegal_values.empty? end
def uniq_spec
self.product.series.each { |series|
errors.add(:spec, 'Non uniq spec for the product.') if series.spec == spec
}
end end
end end
end end
...@@ -69,11 +69,11 @@ RSpec.describe 'Shotengai Models' do ...@@ -69,11 +69,11 @@ RSpec.describe 'Shotengai Models' do
# 非法关键字 # 非法关键字
expect{ expect{
@series.update!(spec: {"颜色" => "红色", "大小" => 1111 }) @series.update!(spec: {"颜色" => "红色", "大小" => 1111 })
}.to raise_error(Shotengai::WebError) }.to raise_error(ActiveRecord::RecordInvalid)
# 关键字缺失 # 关键字缺失
expect{ expect{
@series.update!(spec: {"颜色" => "红色"}) @series.update!(spec: {"颜色" => "红色"})
}.to raise_error(Shotengai::WebError) }.to raise_error(ActiveRecord::RecordInvalid)
end end
it 'Associations' do it 'Associations' do
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment