Rails メモ
rails g migration create_xxxs hoge:integer{8}
みたいなやつに null false
とか渡せないか
結論:
できるのは Rails 4.2 以降で、しかもreferenes
かbelongs_to
の場合のみ
コード:https://github.com/rails/rails/blob/v4.2.0/railties/lib/rails/generators/generated_attribute.rb
def options_for_migration @attr_options.dup.tap do |options| if required? options.delete(:required) options[:null] = false end end end
最初これみて「なんだ、required 渡せばいけるじゃん!」と思ったら、@attr_options にこれが渡ってくる可能性があるケースは references
か belongs_to
だけっぽい。
def parse_type_and_options(type) case type when /(string|text|binary|integer)\{(\d+)\}/ return $1, limit: $2.to_i when /decimal\{(\d+)[,.-](\d+)\}/ return :decimal, precision: $1.to_i, scale: $2.to_i when /(references|belongs_to)\{(.+)\}/ type = $1 provided_options = $2.split(/[,.-]/) options = Hash[provided_options.map { |opt| [opt.to_sym, true] }] return type, options else return type, {} end end
rails g migration create_xxxx hoge:integer{8, index, required}
とかできると熱いのに