How do I add things like default values to migrations from an application template.
For example in template.rb:
generate(:scaffold, "Thing title:string")
What would be the best way to add something like , :default => 'Foo Bar', :null => false
to the line in the migration that creates the title column.
I have two ideas, but don't know if either is possible.
First, can additional attributes be ad开发者_Python百科ded to the column from the generator? Can default values be set when the rails g scaffold
command is called?
Second, could I add a gsub_file
line after the generate line in my template. I don't know how to do gsub_file on a file where part of the file's name is not known (the timestamp on the migration).
Rails-3.1.0
Ruby-1.9.2-p290
Based on @mu_is_to_short's information, I came up with an inelegant solution that does work. Feel free to comment on how to clean it up. In my rails template:
generate "migration add_index_to_users_email"
index_migration_array = Dir['db/migrate/*_add_index_to_users_email.rb']
index_migration_file = index_migration_array.first
in_root { insert_into_file index_migration_file,
"\n add_index :users, :email, unique: true", after: "change" }
rake "db:migrate"
Thor's documentation on in_root
is scanty. I've got a beginner's knowledge of Dir, etc. Thank you for this question and answer! They were what I needed.
If you look at the help:
$ rails generate model --help
Usage:
rails generate model NAME [field:type field:type] [options]
[...]
you won't see any options for specifying anything more than field names and types. AFAIK, you have to edit the generated migration if you want other options.
If you look at the source, you will see things like this:
def generate(what, *args)
log :generate, what
argument = args.map {|arg| arg.to_s }.flatten.join(" ")
in_root { run_ruby_script("script/rails generate #{what} #{argument}", :verbose => false) }
end
So maybe you have access to in_root
(which apparently comes from Thor these days) to put you at the application root so that you can use Dir['db/migrate/*']
to find the migration file; you presumably know the filename except for the leading timestamp and the part of the filename that you know is unique because it maps to a class name. So, you should be able to find the migration file and then you can patch it up as needed.
精彩评论