関数「create」を使用する場合、Enum のマッピング値が正しくありません
概要
現在、Railsをフレームワークとして使用するプロジェクトに取り組んでいますが、オブジェクトを初期化し、enum関数を組み合わせてデータベースに保存する過程で、別の作成者のコードに起因する問題があります。その作者のコードは次のようになります。
notification = Notification.personal.create!(
{
user: target,
template: template,
title: template_language.title_pattern % opts,
content: template_language.content_pattern % opts,
click_action: template.click_action.to_s % opts
}
)
通知.rb
class Notification < ApplicationRecord
include Partition
belongs_to :template
belongs_to :user, optional: true
delegate :notification_category, to: :template, allow_nil: true
has_many :notification_reads, dependent: :destroy
has_many :users, through: :notification_reads
validates :user_id, presence: true, if: :personal?
validates :user_id, absence: true, if: :general?
delegate :notify_partition, to: :user, allow_nil: true
alias_attribute :partition_name, :notify_partition
enum category: {
general: 0,
personal: 1
}
scope :personal_for_user, ->(user_id) { personal.where(user_id: user_id) }
scope :for_user, ->(user_id) { general.or(personal_for_user(user_id)) }
scope :read_personal_notifications, lambda { |user_id, is_read = true|
personal_for_user(user_id).where(is_read: is_read)
}
after_create :increase_total_unread
def be_read_by_user?(reader_id = nil)
return is_read if personal? && user_id == reader_id
if general?
NotificationRead.reset_table_name
return notification_reads.by_user(reader_id).exists?
end
false
end
def read_by(reader_id)
if general?
notification_reads.build(user_id: reader_id)
elsif personal?
user_id == reader_id && self.is_read = true
self
end
end
private
def increase_total_unread
if general?
User.available.update_all('total_unread = total_unread + 1')
elsif personal?
user.increment!(:total_unread)
end
end
end
問題が発生しています。その人が書いたコードは Notice.personal ですが、カテゴリ値 0 のレコードがデータベースに格納されるという問題が時折発生します。
また、いくつかのソースを調べたところ、「create」関数によってオブジェクトがデータベースに即座に保存されることが分かりました。したがって、処理に分岐がある場合、未定義エラーに関する潜在的な問題が発生しますが、新規 + 保存を使用する場合には発生しません。
「create」関数と組み合わせた場合の作成者による列挙型の使用法が正しいのか、それともオブジェクト内の検証関数が原因でこれらの不可解なエラーが発生したのかはわかりません。
私は Java プログラマーで、最近 Ruby プロジェクトに移行したため、Ruby ライブラリのソース コードを読んで理解するのが少し困難です。誰かが私を助けてくれることを願っています。大変感謝しております。
どうもありがとうございます!
解決策
Notice.personal.create!( hash: without, category: :general ) がカテゴリを 0 に設定して通知を作成することはできません。そのレコードは他の呼び出しによって作成されているか、作成後に更新されています。 。