エントリの追加とロールバック

概要

エントリを作成した後、これがログに記録されます。

Started POST "/village_condos" for ::1 at 2024-03-25 08:05:22 +0800
Processing by VillageCondosController#create as HTML
Parameters: {"utf8"=\>"✓", "authenticity_token"=\>"062XY/UorxMa5vG7yH48OpPCwQjv8yn8sTjR/ca60/6CxYUynfaN8IqMbcoTnH/6CXZZYzFi1imMiXBgMBdjMA==", "village_condo"=\>{"name"=\>"Village 2", "village_condo_flag"=\>"1"}, "commit"=\>"Create Village condo"}
User Load (0.5ms)  SELECT  `users`.\* FROM `users` WHERE `users`.`id` = 313 ORDER BY `users`.`id` ASC LIMIT 1
Role Load (0.6ms)  SELECT `roles`.\* FROM `roles` INNER JOIN `roles_users` ON `roles`.`id` = `roles_users`.`role_id` WHERE `roles_users`.`user_id` = 313
(0.1ms)  BEGIN
VillageCondo Create (0.3ms)  INSERT INTO `village_condos` (`name`, `village_condo_flag`, `created_at`, `updated_at`) VALUES ('Village 2', 1, '2024-03-25 00:05:22', '2024-03-25 00:05:22')
(0.3ms)  COMMIT
(0.3ms)  BEGIN
(0.2ms)  ROLLBACK
Redirected to http://localhost:3002/village_condos/596
Completed 302 Found in 38ms (ActiveRecord: 5.0ms)

village_condoテーブルマニフェストに作成されたエントリ(id)を他のテーブルvillage_condo_mappingsにしたいのです(そこにはvillage_condo_idという列があります)。

village_condos テーブルにエントリを正常に追加できますが、village_condo_mappings には反映されません。

これが私のモデルです:

class VillageCondo < ApplicationRecord
  has_many :village_condo_mappings

  validates :name, presence: true, length: { maximum: 150 } # Example: Validate name length
    validates :village_condo_flag, presence: true, inclusion: { in: [1, 2] } # Example: Validate village_condo_flag is either 1 or 2

  after_create :create_village_condo_mapping

  def create_village_condo_mapping
    self.village_condo_mappings.create(village_condo_id: self.id)
  end
end

これはRuby on Rails上にあります。

解決策

次のように試すことができます。

class VillageCondo < ApplicationRecord
  has_many :village_condo_mappings, astosave: true

  validates :name, presence: true, length: { maximum: 150 } # Example: Validate name length
  validates :village_condo_flag, presence: true, inclusion: { in: [1, 2] } # Example: Validate village_condo_flag is either 1 or 2

  befor_create :add_village_condo_mapping

  def add_village_condo_mapping
    self.village_condo_mappings.build
  end
end