Ruby: Trying to "Update_all" but getting "NameError: uninitialized constant" - ruby-on-rails

this is the first time I try to write a ruby migration script (I want to update the value of a col for a specific row).
I have a table called "events" with cols "e_id" and "e_text_en". I want to update the "e_text_en" value of the row with ID 6.
In SQL it would be
update events set e_text_en = 'blabla' where e_id = 6;
My ruby approach: (20141013130000_update_broken_event_texts.rb)
class UpdateBrokenTextsEventInEvent < ActiveRecord::Migration
def Events.up
Events.where('e_id', 6).update_all(e_text_en: "blablabla")
end
end
But this gives me the error ´NameError: uninitialized constant´
rake aborted!
NameError: uninitialized constant UpdateBrokenTextsEventInEvent::Events
/var/.../20141013130000_update_broken_event_texts.rb:2:in `<class:UpdateBrokenTextsEventInEvent>'
/var/.../20141013130000_update_broken_event_texts.rb:1:in `<top (required)>'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:718:in `load_migration'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:714:in `migration'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:708:in `disable_ddl_transaction'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:1012:in `use_transaction?'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:922:in `rescue in block in migrate'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:919:in `block in migrate'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:916:in `each'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:916:in `migrate'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:764:in `up'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/migration.rb:742:in `migrate'
/var/lib/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/railties/databases.rake:42:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:migrate
While I searched for a solution I found some advises that tables are called in singular, but even when I try Event instead of Events I get the same error.
Can anyone help me to correct my ruby?
Versions used:
$ rails -v
Rails 4.0.1
$ gem -v
1.8.23.2
$ ruby -v
ruby 1.9.3p545 (2014-02-24) [i686-linux] Brightbox
edit: Addional infos
Our Schema is created via sql-File. We started to use migrations a short time ago and this is the first update-one. The first two migrations where table-changes. We don't have any ´app/model´ files yet, becuase the other migrations worked without any, e.g.:
class AddDeliveriesToEmailQueue < ActiveRecord::Migration
def change
add_column :email_queue, :deliveries, :int, :null => false, :default => 0, :after => :error
end
end

Firstly your migration class name must match the file name (rails will load the migration file and then assume it created a class of the corresponding name). Assuming you don't change your file name, it means that you need to have
class UpdateBrokenEventTexts < ActiveRecord::Migration
...
end
Since you say that you have no model classes, you'll have to use raw SQL, for example
class UpdateBrokenEventTexts < ActiveRecord::Migration
def change
execute "UPDATE events SET e_text_en = 'blablabla'"
end
end
This is pretty much the same as using ActiveRecord::Base.connection.execute but saves a little on the typing and makes sure Rails understands you're making an irreversible change.

This is a common problem when you create migration and then deside to rename it. Class name in migration should be the same as the filename. You have migration with class UpdateBrokenTextsEventInEvent and filename 20141013130000_update_broken_event_texts.rb, but the class name should be UpdateBrokenEventTexts.

Create Event model:
$ rails g model Event
Assuming that you have a model class Event(inside app/models/event.rb) now, then change these lines:
class UpdateBrokenTextsEventInEvent < ActiveRecord::Migration
def Events.up
Events.where('e_id', 6).update_all(e_text_en: "blablabla")
end
end
to:
class UpdateBrokenTextsEventInEvent < ActiveRecord::Migration
def self.up
Event.where('e_id', 6).update_all(e_text_en: "blablabla")
end
end
Also, I'd recommend you to move such operations in a rake tasks instead of moving them in a migration file:
namespace :events do
desc "Update e_text_en field with blablabla"
task :update_e_text_en => :environment do
Event.where('e_id', 6).update_all(e_text_en: "blablabla")
end
end
and then from your terminal:
$ rake events:update_e_text_en
UPDATE: Don't plan to have a model class for now? No worries, you can still update the column but with a SQL query:
class UpdateBrokenTextsEventInEvent < ActiveRecord::Migration
def self.up
ActiveRecord::Base.connection.execute("UPDATE events SET e_text_en = 'blablabla'")
end
end
Please note that these actions are irreversible(since you don't know what was the previous data in the column you're updating) and that's why they shouldn't be in a migration file. You probably be better with a rake task or something for such operations.

Related

Specified key was too long while migrating

class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :user
t.timestamps
end
end
end
class CreateArticles < ActiveRecord::Migration[6.0]
def change
create_table :articles do |t|
t.string :content
t.timestamps
end
end
end
I created these two entities in a new project and when I run migrate I get this error:
rails db:setup
Created database 'rails_api_development'
Created database 'rails_api_test'
C:/Users/admin/Desktop/projects/rails-api/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter C:/Users/admin/Desktop/projects/rails-api/config/application.rb to limit the frameworks that will be loaded.
admin#Desktop MINGW32 ~/Desktop/projects/rails-api (master)
$ rails db:migrate
rails aborted!
ActiveRecord::StatementInvalid: Mysql2::Error: Specified key was too long; max key length is 1000 bytes
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Caused by:
Mysql2::Error: Specified key was too long; max key length is 1000 bytes
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Also, why does it say mysql2 even though I entered mysql as the database? What the heck is wrong with rails? Is it a problem with the ORM or some other config issues?
SET GLOBAL default_storage_engine = 'InnoDB';
Running this in phpmyadmin solved it. Seems to be an issue with MySQL database.

How do I create this specific PostGres index in a Rails migration?

I’m using Rails 4.2.7 and PostGres 9.5. I’m trying to create a trqm index on my table (to facilitate LIKE searches) so I created this migration
class AddTrqmIndexOnRaceTimes < ActiveRecord::Migration
def change
CREATE INDEX my_object_times_name_gin_trgm_idx ON my_object_times USING gin (name gin_trgm_ops);
end
end
This results in the below error when I run “rake db:migrate” …
StandardError: An error has occurred, this and all later migrations canceled:
undefined local variable or method `gin_trgm_ops' for #<AddTrqmIndexOnRaceTimes:0x007fdc34b40600>
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:664:in `block in method_missing'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'
/Users/mikeb/Documents/workspace/runtrax/db/migrate/20161012185951_add_trqm_index_on_my_object_times.rb:3:in `change'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'
/Users/mikeb/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'
What’s the right way to create this index in a Rails migration?
You cannot add SQL directly in the ruby method change. Either use the add_index method, or if you need to go beyond the capabilities of the helper, use ActiveRecord to execute your query like this:
class AddTrqmIndexOnRaceTimes < ActiveRecord::Migration
def change
MyObjectTime.connection.execute("CREATE INDEX my_object_times_name_gin_trgm_idx ON my_object_times USING gin (name gin_trgm_ops);")
end
end
Rails 5 adds support for specifying operator classes on expression indexes
for example:
def change
add_index :patients, 'lower(last_name) varchar_pattern_ops', name: "index_patients_on_name_unique", unique: true
end
source
ou need to make slight changes to your code. Wrap the sql query in execute.
class AddTrqmIndexOnRaceTimes < ActiveRecord::Migration
def change
execute "CREATE INDEX my_object_times_name_gin_trgm_idx ON my_object_times USING gin (name gin_trgm_ops);"
end
end

Added Column Not accessible in next migration file

I have added a column to my table via a migration, but I am not able to access the added column in the subsequent migration file.
When I execute rake db:migrate the migration aborts, but when I execute it again the migration succeeds, not sure what I am doing wrong. Any help would be appreciated. Thanks.
below is the code where i am adding column
**
class AddIsDispatchToUsers < ActiveRecord::Migration
def change
add_column :users, :is_dispatch, :boolean, :default=>false
end
end
**
Now, when i try to access the column in next migration file it fails.
The subsequent migration file has the code below
service_member = Member.create(:is_dispatch=>true)
And Here is the error that it produces
unknown attribute: is_dispatch/Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1764:in `block in assign_attributes'
/Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1758:in `each'
/Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1758:in `assign_attributes'
/Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1578:in `initialize'
/Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:508:in `new'
/Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:508:in `create'
/Users//Desktop/RailsDevelopement//db/migrate/20161003121452_add_dispatch_services.rb:11:in `up'
Have you tried User.reset_column_information after add_column in same migration.

`block in set_restricted': method column0= doesn't exist (Sequel::Error)

I have this code:
require 'bundler/setup'
require 'sequel'
require 'sequel-rails'
require_relative 'support/benchmark_rails'
DB = Sequel.connect('sqlite::memory:')
COUNT=25
Sequel.extension :migration
Sequel.migration do
change do
create_table(:users) do
primary_key :id
COUNT.times do |i|
column :"column#{i}", "varchar(255)"
end
end
end
end
class User < Sequel::Model; end
attributes = {}
COUNT.times do |i|
attributes[:"column#{i}"] = "Some string #{i}"
end
Benchmark.rails("sequel/#{db_adapter}_create_string_columns", time: 5) do
User.create(attributes)
end
But when I try to run this, it gives the following error:
/home/aaditya/Downloads/ruby-bench-suite/rails/vendor/bundle/ruby/2.3.0/gems/sequel-3.40.0/lib/sequel/model/base.rb:1759:in `block in set_restricted': method name= doesn't exist (Sequel::Error)
from /home/aaditya/Downloads/ruby-bench-suite/rails/vendor/bundle/ruby/2.3.0/gems/sequel-3.40.0/lib/sequel/model/base.rb:1746:in `each'
from /home/aaditya/Downloads/ruby-bench-suite/rails/vendor/bundle/ruby/2.3.0/gems/sequel-3.40.0/lib/sequel/model/base.rb:1746:in `set_restricted'
from /home/aaditya/Downloads/ruby-bench-suite/rails/vendor/bundle/ruby/2.3.0/gems/sequel-3.40.0/lib/sequel/model/base.rb:1257:in `set'
from /home/aaditya/Downloads/ruby-bench-suite/rails/vendor/bundle/ruby/2.3.0/gems/sequel-3.40.0/lib/sequel/model/base.rb:1715:in `initialize_set'
from /home/aaditya/Downloads/ruby-bench-suite/rails/vendor/bundle/ruby/2.3.0/gems/sequel-3.40.0/lib/sequel/model/base.rb:899:in `initialize'
from benchmarks/bm_sequel_create_string_columns.rb:34:in `new'
from benchmarks/bm_sequel_create_string_columns.rb:34:in `<main>'
I tried to simplify this and tried to run only User.create(:name=>'Bob') but with no successful results. What mistake am I making?
There are no problems with the other methods as the same code is running for Active Record.
You are just defining the migration, you aren't actually running the CREATE TABLE on the database. Remove the migration code and just call DB.create_table.
You're creating user with name attribute but you don't have name column in your users table created.

no implicit conversion of Symbol into Integer when migrating in production

So I'm working on an existing app and for some reason I was able to get it working and mirrored on my local environment however when I try migrating on heroku I get the below error, any ideas?
Error:
== 20141119113015 CreateReleasedInventoryStatus: migrating ====================
-- create_enum("eh_released_inventory_status", ["rejected", "pending", "allocated", "released", "transferred"])
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
no implicit conversion of Symbol into Integer/app/vendor/bundle/ruby/2.0.0/gems/power_enum-2.8.0/lib/power_enum/schema/schema_statements.rb:84:in `[]'
/app/vendor/bundle/ruby/2.0.0/gems/power_enum-2.8.0/lib/power_enum/schema/schema_statements.rb:84:in `create_enum'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:662:in `block in method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:632:in `block in say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:632:in `say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:652:in `method_missing'
/app/db/migrate/20141119113015_create_released_inventory_status.rb:3:in `change'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:606:in `exec_migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:590:in `block (2 levels) in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:589:in `block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/connection
Migration file:
class CreateReleasedInventoryStatus < ActiveRecord::Migration
def change
create_enum("eh_released_inventory_status", ["rejected", "pending", "allocated", "released", "transferred"])
end
end
I'm also using the following gem:
gem 'power_enum'
Your migration syntax seems to be incorrect for the power_enum gem that you're using.
The gem's README says the syntax uses a name, then an options hash, such as:
create_enum("status", {…})
Whereas you're using a name, then an array:
create_enum("eh_released_inventory_status", […])
As far as I can tell, the solution is to change your migration line from what you posted to the power_enum syntax. The README has a bunch of examples, and also looks like it's thorough and very well documented.
I think you migration should look like this
class CreateReleasedInventoryStatus < ActiveRecord::Migration
def change
create_enum :released_inventory_status, name_column: :status, description: true, name_limit: 5
["rejected", "pending", "allocated", "released", "transferred"].each do |status|
ReleasedInventoryStatus.update_enumerations_model do |klass|
#0.8.1 < version < 0.9.3 does not yield the klass
#in this case use:
#ReleasedInventoryStatus.create
#in place of klass.create
klass.create :name => status,
:description => status.capitalize
end
end
end
end
This will create the table released_inventory_statuses with status and description columns with a limit of 5 unique statuses. Then it will populate status and description for each item in you list through update_enumeration_model. This should work for your use case but I have not tested this theory. My answer is purely based on how create_enum works and then this section of the README
update_enumerations_model (since version 0.8.1)
The preferred mechanism to update an enumerations model in migrations and similar. Pass in a block to this method to to perform any updates.

Resources