LoginSignup
14
13

More than 5 years have passed since last update.

論理削除とbelongs_to

Last updated at Posted at 2012-08-06

リレーション元を削除したら例外出た、を防ぐために論理削除を実装する。
論理削除系のgemはたくさんあるが、とりあえず定番のrails3_acts_as_paranoidを使う。

Gemfileを書いてbundle

Gemfile
gem "rails3_acts_as_paranoid"

マイグレーションを作成してmigrate

rails g migration AddDeletedAtToCategory deleted_at:timestamp

論理削除するモデル

category.rb
class Cateogory < ActiveRecord::Base
  has_many :items
  acts_as_paranoid
end

リレーション先のモデル

item.rb
class Item < ActiveRecord::Base
  belongs_to :item, :with_deleted => true
end

リレーション

relate.rb
@category = Category.create
@item = category.items.create

リレーション元を論理削除

delete_category.rb
@category.destroy

リレーション先ではまだ参照できる

get_category.rb
p @item.category

論理削除されているかどうかを判定

orphan.rb
p @item.category.deleted? #=> true

リソースにリンクはできない

items_helper.rb
link_to @item.category.name, @item.category #=> categories#indexへのリンクになる

:dependent => :destroyにできない時、したくない時に便利です。
例えば「商品を購入」を中間モデルで表現しているような場合、商品を削除しても購入した記録は残したい時とか。

14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13