Execute method in Rails 4.1.1 migration not working - ruby-on-rails

When I try to run migration for this file:
class AddIndexToUsernameDowncaseForUsers < ActiveRecord::Migration
def up
    execute 'CREATE INDEX index_users_on_username_downcase ON users (lower(username));'
end
def down
remove_index :users, name: :index_users_on_username_downcase
end
end
I get this error:
== 20140521043803 AddIndexToUsernameDowncaseForUsers: migrating ===============
--     execute("CREATE INDEX index_users_on_username_downcase ON groups lower(username);")
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `    execute' for #<AddIndexToUsernameDowncaseForUsers:0x007fea8a9b9c50>/Users/mydir/db/migrate/20140521043803_add_index_to_username_downcase_for_users.rb:3:in `up'
NoMethodError: undefined method `    execute' for #<AddIndexToUsernameDowncaseForUsers:0x007fea8a9b9c50>
/Users/mydir/db/migrate/20140521043803_add_index_to_username_downcase_for_users.rb:3:in `up'
I'm really confused as I've never had issues running migrations before. It looks like the helpers aren't getting included or something. Pretty stumped, but my guess is this is a facepalm-level issue by me.
Rails 4.1.1, Ruby 2.1.1, Postgres 9.3

There are 4 unprintable characters before the word execute - it shows both when it echoes the statement during the migration and also within the quotes in the error: ' execute'.
So it's actually looking for a method called ....execute where .... are those characters.

Related

Devise token auth preventing migration

My rails app is using Devise. I added devise_token_auth so I can link the app to an android app.
In the routes
namespace :api do
scope :v1 do
#mount_devise_token_auth_for 'User', at: 'auth'
end
end
in the initializer
# enable_standard_devise_support = false #for working with Devise
(in addition the other code that was in the file)
I got this error
:~/workspace (master) $ rake db:migrate
-- [](4.2)
-- [](4.2)
rake aborted!
NoMethodError: undefined method `[]' for #<ActiveRecord::Migration:0x00000002c3c470>
Solution, I deleted modified the migration file
class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[4.2]
to
class DeviseTokenAuthCreateUsers < ActiveRecord::Migration
I stopped getting the error but now I got this
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "users" already exists: CREATE TABLE "users" ("id" IN ........
Please help, how can I get this to work?
Try the following steps :
rake db:drop
rake db:create
rake db:migrate

Reversing a specific Rails Migration, can't remove

class UpdateIndexOnUsers < ActiveRecord::Migration
def change
sql = 'DROP INDEX index_users_on_email'
sql << ' ON users' if Rails.env == 'production' # Heroku pg
ActiveRecord::Base.connection.execute(sql)
end
end
I have to undo this migration. When I revert it using rake db:migrate VERSION=20150611173430,I get this error.
StandardError: An error has occurred, this and all later migrations canceled:
PG::SyntaxError: ERROR: syntax error at end of input
LINE 1: CREATE INDEX index_users_on_email
^
: CREATE INDEX index_users_on_email/Users/goda/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'
Then I add a NEW migration file to try and reverse that.
class FixUpdateIndexOnUsers < ActiveRecord::Migration
def change
sql = 'CREATE INDEX index_users_on_email'
sql << ' ON users' if Rails.env == 'production' # Heroku pg
ActiveRecord::Base.connection.execute(sql)
end
end
BUT on heroku, heroku run rake db:migrate fails. Because it runs into that syntax error on the first migration that I cannot remove. What should be done?
EDIT: Fixed syntax, still throwing an error.
PG::SyntaxError: ERROR: syntax error at or near "ON"
LINE 1: DROP INDEX index_users_on_email ON users;
You're using a change method rather than an up, which you should only do for the subset of migrations that rails can reverse automatically.
You should change the change method to up, and add a down method that can reverse the effects of the up method.

Error in DB when trying to generate a model Product

I am going by this tutorial to create a small shopping cart system on rails:http://richonrails.com/articles/building-a-shopping-cart-in-ruby-on-rails
When I run:
rails g model Product name price:decimal{12,3} active:boolean
Then run the rake db:migrate but gives me the following error:
== 20150303175421 CreateProducts: migrating ===================================
-- create_table(:products)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `decimal12' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x00000006a0fd10>/home/ubuntu/workspace/db/migrate/20150303175421_create_products.rb:5:in `block in change'
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/activerecord-4.1.6/lib/active_record/connection_adapters/abstract/schema_statements.rb:198:in `create_table'
Any help? Can't figure it out anywhere...
Thanks
As specified in documentation, you need to put the decimal field description in quotes otherwise rails gets confused and generates two fields.
rails g model Product name 'price:decimal{12,3}' active:boolean
undefined method `decimal12' for #
rails g model Product name 'price:decimal{12,3}' active:boolean
you need to pass it that way on your console: http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration

Why am I getting: Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development

I am a total newbie to Rails, and I am following the Railsbridge Intro to Rails. I have created my project and now I am trying to create a new controller action for voting, and a new route for voting. When I go to the development page, it shows the following message:
Migrations are pending. To resolve this issue, run: bin/rake
db:migrate RAILS_ENV=development
In the command line it gives me this information:
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `migrate' for #<ActiveRecord::ConnectionAdapters::TableDefiniti
on:0x5d79e78>C:/Sites/railsbridgejan/suggestotron/db/migrate/20150129195744_create_votes.rb:6:in `block in change' C:/Sites/railsbridgejan/suggestotron/db/migrate/20150129195744_create_votes.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
So, when I look in my db files for create_votes.rb this is what it looks like:
class CreateVotes < ActiveRecord::Migration
def change
create_table :votes do |t|
t.integer :topic_id
t.string :rake
t.migrate :db
t.timestamps null: false
end
end
end
Is there something wrong with my file's code? t.migrate :db is line 6, which according to the command line, is the problem. I am using Rails 4, Ruby 2, and Sqlite. I had tried to install MySql, but I ran into some major issues, so I just continued with Sqlite. Could that be causing this problem at all? It seems like the issue is in the code listed above, but I'm not sure.
Thank you!
Inside the change method you use
t.migrate :db
The migrate data type doesn't exist. I assume you wanted to use a String.
t.string :db

Rails migration gives error when trying to also create a record in the self.up

I have the following migration:
def self.up
add_column :project_statuses, :system_sequence, :integer, :default => 0, :null => false
ProjectStatus.create :name => 'Declined', :sequence => 35, :system_sequence => 110
...
end
But when I do a rake db:create, rake db:migrate, I get the following error:
== NewProjectStatuses: migrating =============================================
-- add_column(:project_statuses, :system_sequence, :integer, {:default=>0, :null=>false})
-> 0.0029s
rake aborted!
An error has occurred, this and all later migrations canceled:
unknown attribute: system_sequence
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1753:in `block in assign_attributes'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `each'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `assign_attributes'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1567:in `initialize'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `new'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `create'
/[working dir]/db/migrate/20100816100139_new_project_statuses.rb:7:in `up'
The erroneous line number refers to the Project.create :name => ... line.
It seems like the add_column line isn't run at all, even though the output says it is run.
Running a rake db:migrate again runs through the migrations fine though.
Why is this?
Try calling ProjectStatus.reset_column_information after the add_column block.
Rails caches column information (including which columns exist), and I believe what you're hitting here is that you're creating a column, but that doesn't trigger Rails to reset its cache on the list of available columns. As a result, your following line fails, because it doesn't think the column exists.
I'm not sure why the caching is designed this way, but this sort of thing is explicitly mentioned in the example code regarding the use of reset_column_information. I think there's a pretty good chance that's the issue.
That being said, I also generally agree with Michael Durrant, regarding the use of filling the DB with values via migrations. The preferred method is to add your default/seed data to a rake task (which can be run at any arbitrary time), or your seeds.rb file. This is in contrast to a migration, which is only run when the current schema version is older than the specified migration.

Resources