LoginSignup
5
4

More than 5 years have passed since last update.

[ActiveRecord] データベーステーブルのカラム存在チェック方法

Last updated at Posted at 2017-09-25

DBのテーブルに特定のカラムが存在するかどうかをRailsのコードで判定したいケース

ActiveRecord::AttributeMethodsにあるメソッド :arrow_down:

二通り存在するが、それぞれインスタンスメソッドとクラスメソッドという違いがある。
(Railsドキュメントではそのへんまでつっこんでいない)

if User.attribute_present?(:name)
  change
   rename_column :users, :name, :first_name
  end
end

なので、↑のコードだとエラーになる。
NoMethodError: undefined method `attribute_present?' for #<Class:0x*****>

上記のようにmigrationで使用したい場合などは当然インスタンス化などしないので、has_attribute?を使うことになる。

if User.has_attribute?(:name)
  change
   rename_column :users, :name, :first_name
  end
end

こちらは正常に動作する。
以上。

5
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
5
4