4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AR 4.0.1 から joins で default_scope をくっつけてくれる

Posted at

acts_as_paranoid 系を使っているとき joins しても相手方の deleted_at を考慮したスコープが含まれてないので、忘れないように merge(相手方モデル.scope) しとかないといけなかった。でも、Rails 4.0.1 からは勝手につけてくれるようになっていた。付けないメリットより、付け忘れるデメリットの方が多かったのでこの仕様の方がありがたい。

gem "activerecord", "4.0.1.rc1"
require "active_record"
require "paranoid2"

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
  create_table :users do |t|
  end
  create_table :items do |t|
  end
end

class User < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  acts_as_paranoid
end

puts User.joins(:items).to_sql
# >> SELECT "users".* FROM "users" INNER JOIN "items" ON "items"."user_id" = "users"."id" AND "items"."deleted_at" IS NULL

gem "activerecord", "4.0.0" の場合

# >> SELECT "users".* FROM "users" INNER JOIN "items" ON "items"."user_id" = "users"."id"
4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?