ruby
1class User < ActiveRecord::Base
2 has_many :articles
3 before_destroy :unpublish
4
5 private
6 def unpublish
7 Article.where("user_id = ?", self.id).update_all("publish_status = 0")
8 end
9end
上記のようにしておくと@user.destroyでuserの削除前にuserに関連付けられた記事のpublish_statusが変更されます。
Ruby
12.1.7 :008 > Article.all
2 Article Load (0.4ms) SELECT "articles".* FROM "articles"
3 => #<ActiveRecord::Relation [#<Article id: 1, user_id: 2, title: "title 1", created_at: "2016-01-07 11:39:36", updated_at: "2016-01-07 11:50:54", publish_status: 1>, #<Article id: 2, user_id: 2, title: "title 2", created_at: "2016-01-07 11:39:36", updated_at: "2016-01-07 11:50:54", publish_status: 1>]>
42.1.7 :009 > @user.destroy
5 (0.1ms) begin transaction
6 SQL (0.5ms) UPDATE "articles" SET publish_status = 0 WHERE (user_id = 2)
7 SQL (0.2ms) DELETE FROM "users" WHERE "users"."id" = ? [["id", 2]]
8 (2.1ms) commit transaction
9 => #<User id: 2, name: "me", created_at: "2016-01-07 11:50:54", updated_at: "2016-01-07 11:50:54">
102.1.7 :010 > Article.all
11 Article Load (0.4ms) SELECT "articles".* FROM "articles"
12 => #<ActiveRecord::Relation [#<Article id: 1, user_id: 2, title: "title 1", created_at: "2016-01-07 11:39:36", updated_at: "2016-01-07 11:50:54", publish_status: 0>, #<Article id: 2, user_id: 2, title: "title 2", created_at: "2016-01-07 11:39:36", updated_at: "2016-01-07 11:50:54", publish_status: 0>]>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。