Rails thinking sphinx method - mysql

Im trying to set up thinking sphinx in my rails 3 app. I set up mysql and installed sphinx without error. In my gemfile i have
gem "riddle", "~> 1.5.0"
gem "thinking-sphinx", "~> 2.0.10"
These install fine. In my model i have
define_index do
indexes :name
indexes acad_field
indexes expertise
indexes interests
indexes experience
indexes marital_status
indexes email
indexes place_of_birth
indexes birthyear
indexes hometown
indexes current_residence
indexes languages
indexes nationalities
indexes ethnicities_mom_dad
indexes institution
indexes program
end
and in my index in my controller i have
def index
##profiles = Profile.all
#profiles = Profile.search params[:search]
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #profiles }
end
end
in my routes i have
match "profiles?search=:search", :to => "profiles#index"
when i try running a search i get the error
Routing Error
undefined method `define_index' for #<Class:0xb3ada670>
What i am doing wrong here.

I just needed to run
rake thinking_sphinx:rebuild
in terminal

Based on #fuzzyalej comment, the needed steps are:
Replace correspondent gem line to gem "thinking-sphinx", "~> 2.0.10", :require => 'thinking_sphinx'
You do not need add ?search=:search to routing match, because rails can accept GET variables without other specifications.

you probably didn't run 'bundle install' after adding the gem specification in your gemfile, I don't think rake ts:rebuild actually solved this issue :)

Related

ActionController::RoutingError (Couldn't find..., expected it to be defined in...)

So...first time asking a question to StackOverflow...
I converted an existing Rails 4.2.5 app (using Ruby 2.2.4) to a Rails 5.1.3 app (using Ruby 2.4.1), following the Rails Guides and the RailsApps Project.
Firing up the development server produces:
Taruns-iMac:Play_Ball tarunchattoraj$ rails s
=> Booting Puma
=> Rails 5.1.3 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.9.1 (ruby 2.4.1-p111), codename: Private Caller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
which is what I would expect.
Navigating to localhost:3000, however, produces an the ActionController error:
Started GET "/" for 127.0.0.1 at 2017-08-13 11:05:38 -0400
(0.2ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
ActionController::RoutingError (Couldn't find Api::KeepScoresHelper, expected it to be defined in helpers/api/keep_scores_helper.rb):
app/controllers/application_controller.rb:1:in `<top (required)>'
app/controllers/welcome_controller.rb:1:in `<top (required)>'
I expected to see my app running on the page normally.
My Question:
What is causing this ActionController::RoutingError (Couldn't find...) and how to correct it?
This question seems to be on point. I tried the solution of "touching" all the helper files but to no avail.
When I converted from Rails 4.2.5 to 5.1.3, I ran $ rails app:update and I overwrote most files--those in which I didn't have code specific to my app, but I chose not to overwrite config/routes.rb.
config/routes.rb:
Rails.application.routes.draw do
resources :alerts
get 'games/decide_game_view' => 'games#decide_game_view', as: :decide_game_view
resources :games
resources :game_hitting_stats
resources :game_pitching_stats
resources :locations
resources :players
get 'welcome/index'
get 'welcome/about'
resources :users do
resources :players
end
resources :sessions, only: [:new, :create, :destroy]
resources :teams do
resources :notes
end
# namespace :api, defaults: {format: :http} do
namespace :api do
match '/texts', to: 'texts#preflight', via: [:options]
resources :texts, only: [:create]
match '/keepscore/teams', to: 'keep_scores#preflight', via: [:options]
get 'keepscore/teams' => 'keep_scores#get_teams', as: :get_teams
match '/keepscore/roster', to: 'keep_scores#preflight', via: [:options]
get 'keepscore/roster' => 'keep_scores#get_roster', as: :get_roster
match '/keepscore/post_game_stats', to: 'keep_scores#preflight', via: [:options]
post 'keepscore/post_game_stats' => 'keep_scores#post_game_stats', as: :post_game_stats
end
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
root 'welcome#index'
end
ActionController seems to be telling me that it can't find the KeepScoresHelper Module and that its looking in helpers/api/keep_scores_helper.rb. But that file exists See Pic of App Controller and Helper Tree Structure.
The contents of helpers/api/keep_scores_helper.rb:
module API::KeepScoresHelper
end
Gemfile:
source 'https://rubygems.org'
ruby "2.4.1"
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '5.1.3'
gem 'puma'
gem 'pundit'
gem 'bcrypt'
gem 'active_model_serializers', '~> 0.10.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
gem 'jquery-turbolinks'
gem 'bootstrap-sass'
gem 'figaro'
gem 'pry'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :production do
gem 'pg'
gem 'rails_12factor'
end
group :test do
gem 'pundit-matchers', '~>1.0.1'
end
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'listen'
gem 'byebug'
gem 'web-console', '~> 3.5.1'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'rspec-rails'
gem 'shoulda'
gem 'faker'
gem 'factory_girl_rails'
gem 'rails-controller-testing'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'sqlite3'
end
Of course any help is greatly appreciated...
In config/environments/development.rb, set:
config.action_controller.include_all_helpers = false
This returns Helpers to pre-Rails 5 behavior. Per RoR API, for Rails 5.1.3, "By default, each controller will include all helpers." Pre Rails 5, the controller would include a helper matched to its name. Making the setting as specified above returns to the Pre-Rails 5 behavior.
Adding in hopes of helping others that stumble across this.
Initial Trouble Shooting
I had this same issue when upgrading the same versions you mention in your question. I did upgrade from 4.2 to 5.0 first though then upgrade to 5.1.3 from there.
The first upgrade worked fine but I started receiving the same error message (e.g. uninitialized constant ActionController::RedirectBackError ... about not being able to find the helpers but this only happened when I jumped to rails 5.1.
I tried a lot of other fixes as outlined in this github issue as it seemed to be the same error but nothing worked and my paths all seemed to be correct (no discrepancies in path or casing).
My Fix
I ended up deleting all helpers and received a new error which lead me to finding the code in my app that was causing the problem.
# app/controllers/application_controller.rb
# Catch exceptions if :back is not set throughout the app. This is a fallback redirect if request.referer is not set.
rescue_from ActionController::RedirectBackError do |exception|
redirect_to key_activities_ministries_activities_path, alert: exception.message
end
That code was causing a Routing Error: uninitialized constant ActionController::RedirectBackError. But this error only appeared when I removed all of my helpers. I removed this code, put my helpers back, and restarted my server and everything worked as expected.

Can't run a db migration on rails

I have had ongoing trouble migrating a database in rails via rake db:migrate.
My migration currently looks like this:
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :title
t.text :subtitle
t.string :slug
t.text :body
t.integer :publish, limit: 1, default: 0
t.timestamps
end
end
end
However if ever I delete a column from this or even add or modify one the rake db:migrate command does nothing. The only way I can migrate it is sometimes running something like:
rake db:migrate VERSION=20080906120000
But even that is temperamental so most of the time I need to reset the db using
db:drop
db:create
then running the migration again as normal. basically db:migrate only ever works the first time after dropping and creating the db.
I've also tried rollback before running the migration.
This is far from ideal so I'd appreciate any help.
(I realise there are similar questions but all of their issues are solved after a db reset)
You need to run the migration down and then run it up again, which is done with the redo task. try this:
rake db:migrate:redo VERSION=20080906120000
EDIT: if you have data you want to keep in this table, it's better to make a new migration to remove the column or whatever you want to do, as the above will drop and recreate the table, wiping the data in the process.

ActiveRecord::IrreversibleMigration exception when reverting migration

I have created the following Active Record Migration that adds and removes some indexes.
class FixIndexes < ActiveRecord::Migration
def change
add_index :table1, :field1, :unique => true
remove_index :table2, :name => "index_table2_on_field1"
remove_index :table2, :name => "index_table2_on_field2"
remove_index :table3, :name => "index_table3_on_field1"
add_index :table3, [:field1, :field2]
end
end
When I run the migration ($ bundle exec rake db:migrate) it works fine as expected.
Unfortunately when I try to revert the migration ($ bundle exec rake db:rollback) it does not work and raises an ActiveRecord::IrreversibleMigration exception
== FixIndexes: reverting =====================================================
rake aborted!
An error has occurred, all later migrations canceled:
ActiveRecord::IrreversibleMigration/usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-3.2.14/lib/active_record/migration/command_recorder.rb:42:in `block in inverse'
/usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-3.2.14/lib/active_record/migration/command_recorder.rb:40:in `map'
My questions are:
Why this is an irreversible migration? It just adding and
removing some indexes, not data.
It will fix the problem if I use def self.up and def self.down
instead of def change?
How can I revert now this changes without adding and removing the
indexes manually from MySQL?
Only few commands are reversible(without manual commands) in Rails. And they are
add_column
add_index
add_timestamps
create_table
create_join_table
remove_timestamps
rename_column
rename_index
rename_table
Refer here
Your migration contains remove_index which is not supported by CommandRecorder for Rollback.
If you check this Documentation
Some transformations are destructive in a manner that cannot be
reversed. Migrations of that kind should raise an
ActiveRecord::IrreversibleMigration exception in their down method.
Which is the case in yours and obviously results in ActiveRecord::IrreversibleMigration exception.
Long Story short: remove_index cannot be reversed without manual commands.

can't activate mysql2 (~> 0.3.6), already activated mysql2-0.3.2 in Rails 3.1

I'm just trying to get the most basic of basic shell of a rails app running under 3.1, and I'm getting this weird error when I run bundle exec rake db:migrate-
Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` (can't activate mysql2 (~> 0.3.6), already activated mysql2-0.3.2. Make sure all dependencies are added to Gemfile.)
All the posts that I've read here and elsewhere say I should be using the newer mysql2 adaptor for rails 3.1, so I have-
gem 'mysql2', '0.3.2'
in my gemfile. Some post have suggested using-
gem 'mysql2', '~> 0.3'
but that gets me the same error. The gem is installed at-
/Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/mysql2-0.3.2
It was suggested that I switch up that line in my gemfile again, this time to be-
gem 'mysql2', '< 0.3'
but when I do that, run bundle install, and then try to run migrations again, I get-
An error has occurred, all later migrations canceled:
undefined method `rows' for nil:NilClass
My complete migration file looks like this-
class CreatePlaces < ActiveRecord::Migration
def change
create_table :places do |t|
t.string :title
t.string :meta_description
t.string :permalink, :limit => 60
t.string :name, :limit => 60
t.string :address
t.string :state, :limit => 2
t.string :region, :limit => 3
t.float :latitude
t.float :longitude
t.text :description
t.boolean :active, :default => true
t.timestamps
end
add_index :places, [:permalink, :state, :region, :latitude, :longitude, :active], :name => 'places_index'
end
end
And the full output of running that migration is-
== CreatePlaces: migrating ===================================================
-- create_table(:places)
-> 0.0925s
-- add_index(:places, [:permalink, :state, :region, :latitude, :longitude, :active], {:name=>"places_index"})
-> 0.1097s
== CreatePlaces: migrated (0.2023s) ==========================================
rake aborted!
An error has occurred, all later migrations canceled:
undefined method `rows' for nil:NilClass
There are no later migrations, that's the only one, as this is an app that I'm just starting to try to get Rails 3.1 running properly. Dropping the database and recreating it gets me to the same place.
I am able to access Places from the console-
ruby-1.9.2-p180 :001 > Place
(0.3ms) SHOW TABLES
(0.1ms) SHOW TABLES
(1.1ms) describe `places`
=> Place(id: integer, title: string, meta_description: string, permalink: string, name: string, address: string, state: string, region: string, latitude: float, longitude: float, description: text, active: boolean, created_at: datetime, updated_at: datetime)
But when I actually try to do a find or anything on Places, I get the following error-
Place.find(:all)
ArgumentError: wrong number of arguments (3 for 2)
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/mysql2-0.2.7/lib/active_record/connection_adapters/mysql2_adapter.rb:634:in `select'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/activerecord-3.1.0.rc5/lib/active_record/connection_adapters/abstract/database_statements.rb:9:in `select_all'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/activerecord-3.1.0.rc5/lib/active_record/connection_adapters/abstract/query_cache.rb:62:in `select_all'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/activerecord-3.1.0.rc5/lib/active_record/base.rb:470:in `find_by_sql'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/activerecord-3.1.0.rc5/lib/active_record/relation.rb:111:in `to_a'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/activerecord-3.1.0.rc5/lib/active_record/relation/finder_methods.rb:155:in `all'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/activerecord-3.1.0.rc5/lib/active_record/relation/finder_methods.rb:105:in `find'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/activerecord-3.1.0.rc5/lib/active_record/base.rb:437:in `find'
from (irb):2
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/railties-3.1.0.rc5/lib/rails/commands/console.rb:45:in `start'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/railties-3.1.0.rc5/lib/rails/commands/console.rb:8:in `start'
from /Users/mark/.rvm/gems/ruby-1.9.2-p180#rails310pre/gems/railties-3.1.0.rc5/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Anyone have any ideas? I've been digging for like 18 hours now, and just running in circles.
Thanks,
--Mark
Active Record has it's own requirements on which versions of mysql2 are compatible. Here's the line of code for Rails 3.1. You must use a version of mysql2 that satisfies these requirements.
Please install the mysql2 adapter: gem install activerecord-mysql2-adapter (can't activate mysql2 (~> 0.3.6), already activated mysql2-0.3.2. Make sure all dependencies are added to Gemfile.)
This is saying Rails expects a mysql2 version greater than 0.3.6 and less than 0.4.0, but found version 0.3.2. If you change your Gemfile to request a version in this range then Active Record should be happy. Perhaps
gem 'mysql2', '0.3.6'
Don't forget to update your bundle after changing your Gemfile.
bundle update mysql2
I know this is a very old thread but because it still comes up in Google results a one of the first results I though I would updated it with I had to do work around this issue in newer versions of Rails.
The errors shows as:
Gem::LoadError: Specified 'mysql2' for database adapter,
but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile
followed by:
Gem::LoadError: can't activate mysql2 (< 0.5, >= 0.3.13),
already activated mysql2-0.5.2. Make sure all dependencies are
added to Gemfile.
I already had the gem added in my Gemfile as shown below:
group :production do
gem 'mysql2'
end
but I had to update it to prevent from picking up a version outside of the range indicated in the error message. Notice the '< 0.5' below:
group :production do
gem 'mysql2', '< 0.5'
end
Additionally, different versions of Rails set different min/max version restrictions for the MySQL gem:
From
https://github.com/brianmario/mysql2/issues/950#issuecomment-376375844
"Correct, Rails 4.x cannot use mysql2 0.5.x. The actual code would
work fine, but Rails 4 has a version restriction in place to prevent
use of mysql2 0.5.x. This is intentional, as it allows future changes
to the API without silently risking their use in older code not
prepared to use the new APIs. There's also nothing magic about the
version numbers -- it's totally by coincidence that Rails 4 uses
mysql2 0.4 and Rails 5 will be able to use mysql2 0.4 or 0.5."
This also had me pulling out my hair. To only reasonable solution I could get was to switch to the master branch of the mysql2 gem.
gem 'mysql2', :git => 'git://github.com/brianmario/mysql2.git'
After this update my Rails 3.1.0.rc5 application could start with MySQL. (At the time of this post the latest version of the gem was 0.3.6)
I have the same issue several times with an Redmine implementation.
I changed a gem line place on
RUBYGEM#VERSION/gems/activerecord-3.2.22.2/lib/active_record/connection_adapters/mysql2_adapter.rb
In the line 3 change this
gem 'mysql2', '~> 0.3.10'
with this
gem 'mysql2', '~> 0.4.10' (or whatever version you need)
And all works fine
if anyone here is stuggling with this in 2022 with the new M2 book
"can't activate mysql2 (~> 0.3.10), already activated mysql2-0.5.2"
you have to update this file:
/usr/local/bundle/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/mysql2_adapter.rb:3
and change it to the version of the mysql gem you are using.
Pretty old question, so I'm assuming the original poster has already solved the issue. However, in case anyone is coming to this post trying to solve the first issue:
Please install the mysql2 adapter: gem install activerecord-mysql2-adapter (can't activate mysql2 (~> 0.3.6), already activated mysql2-0.3.2. Make sure all dependencies are added to Gemfile.)
This is most likely occurring because you are not running your migrations via bundle exec. Try running bundle exec rake db:migrate.

Rolling back a failed Rails migration

How do you roll back a failed rails migration? I would expect that rake db:rollback would undo the failed migration, but no, it rolls back the previous migration (the failed migration minus one). And rake db:migrate:down VERSION=myfailedmigration doesn't work either. I've ran into this a few times and it's very frustrating. Here's a simple test I made to duplicate the problem:
class SimpleTest < ActiveRecord::Migration
def self.up
add_column :assets, :test, :integer
# the following syntax error will cause the migration to fail
add_column :asset, :test2, :integer
end
def self.down
remove_column :assets, :test
remove_column :assets, :test2
end
end
result:
== SimpleTest: migrating =====================================================
-- add_column(:assets, :test, :integer)
-> 0.0932s
-- add_column(:asset, :error)
rake aborted!
An error has occurred, all later migrations canceled:
wrong number of arguments (2 for 3)
ok, lets roll it back:
$ rake db:rollback
== AddLevelsToRoles: reverting ===============================================
-- remove_column(:roles, :level)
-> 0.0778s
== AddLevelsToRoles: reverted (0.0779s) ======================================
huh? that was my last migration before SimpleTest, not the failed migration. (And oh, it would be nice if the migration output included the version number.)
So lets try running the down for the failed migration SimpleTest:
$ rake db:migrate:down VERSION=20090326173033
$
Nothing happens, and no output either. But maybe it ran the migration anyway? So lets fix the syntax error in the SimpleTest migration, and try to run it again.
$ rake db:migrate:up VERSION=20090326173033
== SimpleTest: migrating =====================================================
-- add_column(:assets, :test, :integer)
rake aborted!
Mysql::Error: Duplicate column name 'test': ALTER TABLE `assets` ADD `test` int(11)
Nope. Obviously the migrate:down didn't work. It's not failing, it's just not executing.
No way to get rid of that duplicate table other than manually going into the database and removing it, and then running the test. There's got to be a better way than that.
Unfortunately, you must manually clean up failed migrations for MySQL. MySQL does not support transactional database definition changes.
Rails 2.2 includes transactional migrations for PostgreSQL. Rails 2.3 includes transactional migrations for SQLite.
This doesn't really help you for your problem right now, but if you have a choice of database on future projects, I recommend using one with support for transactional DDL because it makes migrations much more pleasant.
Update - this is still true in 2017, on Rails 4.2.7 and MySQL 5.7, reported by Alejandro Babio in another answer here.
OK, folks, here's how you actually do it. I don't know what the above answers are talking about.
Figure out which part of the up migration worked. Comment those out.
Also comment out/remove the part of the migration that broke.
Run the migration again. Now it will complete the non-broken parts of the migration, skipping the parts that have already been done.
Uncomment the bits of the migration you commented out in step 1.
You can migrate down and back up again if you want to verify that you've got it right now.
To go to a specified version just use:
rake db:migrate VERSION=(the version you want to go to)
But if a migration fails part way, you'll have to clean it up first. One way would be:
edit the down method of the migration to just undo the part of the up that worked
migrate back to the prior state (where you started)
fix the migration (including undoing your changes to the down)
try again
I agree that you should use PostgreSQL when possible. However, when you are stuck with MySQL, you can avoid most of these problems by trying your migration on your test database first:
rake db:migrate RAILS_ENV=test
You can revert to the previous state and try again with
rake db:schema:load RAILS_ENV=test
At 2015 with Rails 4.2.1 and MySQL 5.7, a failed migration can't be fixed with standard rake actions that Rails provide, as it was at 2009.
MySql does not support rollback of DDL statments (at MySQL 5.7 Manual). And Rails can not do anything with that.
Also, we can check how Rails is doing the job: A migration is wrapped in a transaction depending on how connection adapter respond to :supports_ddl_transactions?. After a search of this action at rails source (v 4.2.1), I found that only Sqlite3 and PostgreSql supports transactions, and by default it is not supported.
Edit
Thus the current answer to the original question: A failed MySQL migration must be manually fixed.
The easy way to do this is to wrap all of your actions in a transaction:
class WhateverMigration < ActiveRecord::Migration
def self.up
ActiveRecord::Base.transaction do
...
end
end
def self.down
ActiveRecord::Base.transaction do
...
end
end
end
As Luke Francl noted, "MySql['s MyISAM tables don't] support transactions" -- which is why you might consider avoiding MySQL in general or at least MyISAM in particular.
If you're using MySQL's InnoDB, then the above will work just fine. Any errors in either up or down will back out.
BE AWARE some types of actions cannot be reverted via transactions. Generally, table changes (dropping a table, removing or adding columns, etc.) cannot be rolled back.
Run just the down migration from the console:
http://gilesbowkett.blogspot.com/2007/07/how-to-use-migrations-from-console.html (click through to his pastie)
I had a typo (in "add_column"):
def self.up
add_column :medias, :title, :text
add_colunm :medias, :enctype, :text
end
def self.down
remove_column :medias, :title
remove_column :medias, :enctype
end
and then your problem (cannot undo partly failed migration). after some failed googling i ran this:
def self.up
remove_column :medias, :title
add_column :medias, :title, :text
add_column :medias, :enctype, :text
end
def self.down
remove_column :medias, :title
remove_column :medias, :enctype
end
as you can see i just added the correction line by hand, and then removed it again, before i checked it in.
Alejandro Babio's answer above provides the best current answer.
One additional detail I want to add:
When the myfailedmigration migration fails, it is not considered as applied, and this can be verified by running rake db:migrate:status, which would show output similar to the following:
$ rake db:migrate:status
database: sample_app_dev
Status Migration ID Migration Name
--------------------------------------------------
up 20130206203115 Create users
...
...
down 20150501173156 Test migration
The residual effect of add_column :assets, :test, :integer being executed on the failed migration will have to be reversed at the database level with a alter table assets drop column test; query.