Just learning rails, am on to migrations and it all started off pretty logically until I hit something odd going on in the code;
rails generate migration AddRegionToSupplier
The above produces a migration file with only a "def change" method in it.
I googled this and found that this is exactly what is supposed to happen;
http://guides.rubyonrails.org/migrations.html
I would have expected it to generate a "def up" and "def down" method, so that the migration could be rolled back. Have I done something wrong in the generation or am I missing something obvious?
From the link you pasted:
Rails 3.1 makes migrations smarter by providing a new change method.
This method is preferred for writing constructive migrations (adding
columns or tables). The migration knows how to migrate your database
and reverse it when the migration is rolled back without the need to
write a separate down method.
So it looks like you don't have to worry about having a def self.down as Rails is now smart enough to know how to roll it back.
Related
I have a model called MyArticle. When I try to use the command
rails generate migration AddtestToMyArticle test:string
the migration file contains only empty up/down methods. Having done this previously on a single word model name, it worked just fine and the migration up/down methods had the appropriate code.
I tried "AddtestToMy_Article" but that didn't work either. What do I need to do to work with my compound model name and the generate migration command?
You need to use
rails generate migration AddColumnToMyArticle test:string
When using 'AddColumn' you will have the appropriate code in your migration.
I just looked back over this, and while my answer is correct, it's better to have a more descriptive migration name. The user below who noticed the capitalization is right in that if you don't have each new word capitalized, Rails won't pick up on what exactly you're trying to do. So, in your question you have AddtestTo... but it should be AddTestTo....
It seems to work if you use underscores rather than CamelCase
rails g migration add_test_to_my_article test:string
Hope this helps
rails generate migration AddNewFieldToMyArticle new_field:string
I generated a rails 3.2 migration with an empty down function, because the migration is irreversible (and I don't want to throw an exception). I run the migration successfully, but it has no effect. When I rollback, and run db:migrate again, the effects does apply.
I solved this easily by filling the empty down function with a code which does nothing, but it's still pretty ugly.
Does anyone knows why this happens? Is this a rails bug?
The exception is throwed to prevent destroying your database, if its irreversable, then that's probably the right thing to do.
Your #down could look like this:
def down
raise ActiveRecord::IrreversibleMigration, "Explain why its irreversable!"
end
That will save others a lot of headache as it clearly notifies about irreversable migration and explains the reason behind it :)
EDIT: I cannot confirm this behaviour for Rails 3.2.3. I've created several different migrations without #down, and no exceptino was raised. Maybe it's something in your code, which you didn't show a bit.
EDIT 2: Just to recap, when you're using up/down method, its your responsibility to raise ActiveRecord::IrreversibleMigration. In other case, nothing will happen (#down defined in AR will just return nil). The behaviour is different when you use #change. In some cases the mentioned exception can be raised by #inverse defined here: https://github.com/rails/rails/blob/565bfb9cd49285ebaa170141b4996c22ba81de43/activerecord/lib/active_record/migration/command_recorder.rb#L39 which is expected behaviour.
I made a standard Active::Record class with a user_id field on it, and sure enough, the requirements changed. Turns out I needed to nix the 'user_id' column, and put on an 'email' column instead. I figured I would just manually replace the field in the migration file and then do a quick 'rake db:migrate down/up' on that version to make the update. I even ended up updating db/schema.rb as well.
No Dice:
Failure/Error: ss = Factory(:model)
undefined method `email=' for #<Model:0xb2cc288>
I can use email getter/setter methods in the console, or in the service fine -- but factory girl doesn't seem to get the hint. Is it caching a method list somewhere? (Hint: mysql table looks good too)
Firstly, in the future, try really hard not to change existing migration files. You will mess up more than just FactoryGirl, namely you will mess up your teammates' setups. Requirements change and that's OK, you just make a new migration that drops the user_id column and adds an e-mail column. This way, the evolution of the data model will be recorded in the migrations.
For your specific problem, though, you probably want to run rake db:test:prepare or, if that doesn't work, drop your test database completely and rebuild it.
I have an app that I've converted over from another cms. The old URLs were being stored in the database like so:
/this-is-an-old-permalink/
And I need them to be like this:
this-is-an-old-permalink
Note the absence of forward slashes. What is the easiest way to go about removing them?
I'm not necessarily looking for the exact code to do it (although that'd be nice!) -- I'm asking also as a Rails newb: What is the best method to go about doing things like this? I've only really worked with Rails in setting up a model, controller, views and outputting data. I haven't had to do any processing like this. Would it go in the model? Any help is appreciated!
edit
Do I need to get all records, loop through them, do regex on that one field and then save it?
Since you're likely only going to write this once, your best bet is to create a script for it within lib, or to write a migration for it. I recommend the latter, because it will then be executed automatically with rake db:migrate if you restore from your old backup at a later date. You can then use all your standard Model processing tricks (like you would use on a Controller) within the migration without exposing the substitution code to a Controller.
EDIT:
You can add the following to a new file within lib/tasks to create a new rake task for this called db:substitute_slashes:
namespace :db do
desc "Remove slashes from old-style URLs"
task :substitute_slashes => :environment do
Modelname.find(:all).each do |obj|
obj.fieldname.gsub!(/regex here/,'')
obj.save!
end
end
end
The exclamation on the end of save! means it will throw an exception if the resulting object fails validation, which is a good thing to check for in this case.
You would then be able to execute this with the command rake db:substitute_slashes.
I have a bunch of rails models that I'm re-writing into a single model to simplify my code and reduce unnecessary tables.
I'm wondering what the best way to delete a model class and its table is. I want past migrations to still succeed, but I don't want to leave the empty models lying around.
Do I have to manually delete the old migrations that reference these models, then manually delete the class files?
Does anyone have any tips for the best way to do this?
All in one solution.
Run the following commands:
rails destroy model ModelName
rails g migration DropTableModelName
The former will generate a new migration file which should looks like this:
class DropTableModelName < ActiveRecord::Migration
def change
drop_table :model_name
end
end
Now run db:migrate and you're done.
If you'd like to completely get rid of of a model and its table do this:
rails destroy model Name
The question is a bit stale now, but I just did:
rails destroy scaffold <ModelName> -p
The -p flag shows "pretend" output, which is good for seeing what will happen. Remove the '-p' flag and the results will match the output. This cleaned the entire collection of M-V-C files + testing + js files + the original migration, no problem.
I guess if you are one who likes to hand edit your migrations and include multiple steps in each, losing the original migration could break db:setup, so buyer beware. Keeping one action == one migration file should avoid this potential snafu.
What about doing ruby script/destroy model? That should take care of the model and the migration.
Depending on how far into development or production you are, you may want to migrate the models out safely using a migration to remove/backup data or what not. Then as bobbywilson0 suggested, using
script/destroy model
or if you rspec anything
script/destroy rspec_model
This will remove any spec tests as well.
Or you can always just drag them to the trash folder.
You can take a look at this one at rails guide.
But I suggest, if it is possible, you should delete the models and all references to the models. This will probably save time later as you don't need to maintain the dead code in the codebase.
If you'd rather have a manual based answer:
First run the following command to identify which migrations you want removed:
rake db:migrate:status
Feel free to grep -i on it too if you're confident of your naming scheme.
Make note of all the "add x to model name" and similar alterations to your Model. These can be removed using:
rails d migration AddXToModelName
Do this for every migration besides the initial create migration. The following command will take care of the initial create migration and the files associated with the model:
rails d model ModelName