Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check constraints on table columns using Rails?

If I don't use the annotate gem, how do I check the constrains that are on my table's columns? I can use rails console to see what columns are on which tables but I can't see the constraints like not null.

like image 683
stackjlei Avatar asked Jun 26 '17 16:06

stackjlei


2 Answers

Any ActiveRecord subclass has columns method, that returns all metadata about columns for underlying table:

User.columns.find { |c| c.name == 'email' }.null
# => false
like image 182
mikdiet Avatar answered Nov 13 '22 23:11

mikdiet


Without annotate, the easiest way from vim/text editor would be to look in the db/schema.rb file. This file is a culmination of all of your migrations and represents the current state of your database schema.

It will look very similar to a migration file. Here's an example:

ActiveRecord::Schema.define(:version => 11) do
  create_table "users", :force => true do |t|
    t.string   "email", default: "", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "remember_token"
    t.datetime "remember_token_expires_at"
  end
end

As you can see on the email column, it may not be null (not null). Some other parameters may look like limit: 20 for character limits, etc. More column definitions are provided in the docs

like image 30
codelitt Avatar answered Nov 13 '22 22:11

codelitt