Table 'project_dev.users' doesn't exist - mysql

I just created a new table using a Rails migration, then I created a model where I added in its relationships.
I have restarted my console, and the MySQL console shows the table in the project_dev database.
When I try to create a new record in my Ruby console, I get:
Mysql::Error: Table 'project_dev.trace_users' doesn't exist
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.1/lib/act
ive_record/connection_adapters/mysql_adapter.rb:287:in 'query'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.1/lib/act
ive_record/connection_adapters/mysql_adapter.rb:287:in 'execute'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.1/lib/act
ive_record/connection_adapters/mysql_adapter.rb:438:in 'columns'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.1/lib/act
ive_record/base.rb:679:in 'columns'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.1/lib/act
ive_record/persistence.rb:285:in 'attributes_from_column_definition'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.1/lib/act
ive_record/locking/optimistic.rb:62:in 'attributes_from_column_definition'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.1/lib/act
ive_record/base.rb:1396:in 'initialize'
from (irb):2:in 'new'
from (irb):2
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.1/lib/rails/c
ommands/console.rb:44:in 'start'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.1/lib/rails/c
ommands/console.rb:8:in 'start'
from C:/Sanj/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.1/lib/rails/c
ommands.rb:23:in '<top (required)>'
from script/rails:6:in 'require'
from script/rails:6:in '<main>'

It seems I was a little more incompetent yesterday than I'd otherwise like to admit - the migration tables had been created in singular form instead of plural - this led to the table trace_user instead of trace_users.
#Ben - I called the table that because I have a few trace tables in the system recording different kinds of events, and I preferred to have all the trace tables together - IMHO this helps to make the tables easier to understand when trying to comprehend the system as a whole.

You had a User model and then added a Trace model, right? You did everything right, except that since you added has_many users in Trace, you now have to create the association table (through another migration). Consider getting the association direction correct (user has_many traces?) so that the table is user_traces, which to me sounds better.

Related

(1054, "Unknown column '' in 'field list'")

I know this question has been asked a couple of time but no previous answer was able to solve my problem.
I had a perfectly working model in Django that looked like this:
class Template(models.Model):
mat = models.CharField(max_length=50, null=True)
...
I had many instances of this model and up to now I was very happy with it. I recently decided that instead of a Charfield, this model was better suited to work with a ForeignKey in this position instead.
To get into details, the attribute ''mat'' was previously only referring to the name of another object instance. I decided to change it to the full fledged instance with a ForeignKey instead, like it should have always been. Therefore, the model was modified as follows:
class Template(models.Model):
mat = models.ForeignKey(Stock, on_delete=models.CASCADE, related_name='mat_stock', verbose_name="mat", null=True)
...
I followed this change with the regular */manage.py makemigrations, */manage.py migrate. While these two commands worked, I was unable to select any instance of Template in the shell without raising the following error:
OperationalError: (1054, "Unknown column 'myapp_template.mat_id' in 'field list'")
Similar situations I encountered were solved by manually adding a column in SQL with the following line:
ALTER TABLE database.myapp_template ADD mat INT;
Unfortunately this did not solve my problem.
I figured maybe the problem was that I already had instances of my object that had character values in the ''mat'' column. Django would expect integer values (specifically "id") after my migration, so I decided to create a completely new attribute for Template as follows:
class Template(models.Model):
pos_mat = models.ForeignKey(Stock, on_delete=models.CASCADE, related_name='mat_stock', verbose_name="mat", null=True)
...
This, I thought, would delete (or disregard) the "mat" column and create new "pos_mat" columns with the desired properties without having to handle old character values that wouldn't fit with the requirements. From there on it should be like adding a completely new ForeignKey attribute.
After the required and successful */manage.py makemigrations, */manage.py migrate I am still unable to access an instance of my model in the shell. I still get the same unpleasing:
OperationalError: (1054, "Unknown column 'myapp_template.mat_id' in 'field list'")
Would anybody know how to convince Django to go along with my changes? I am skeptical that rolling back migrations to zero will help me (it did not solve my problems in the past) and I hope it will not come to the deletion of my data. It is acceptable for my model to have an empty field in this column since I added a null=True to my attribute.
Thank you very much for your help. Have a good day.
I have solved my problem by rolling back to my last stable migration. From there I was able to migrate a model where 'mat' was absent and 'pos_mat' was the only attribute. This means my problem arose in the first migration from the old version of 'mat' to the new version of 'mat'. Basically keeping the same name but changing the attribute characteristics is a no go. I hope those with the same problem will be able to fix it with this.

Rails Mysql2::Error Table doesn't exist When create new migration

I wrote a migration with the following (create new table named sources):
class CreateSources < ActiveRecord::Migration
def change
create_table :sources do |t|
t.string :name, null: false, default: ""
t.timestamps null: false
end
end
end
And then I modified my existing model :
class Property < ActiveRecord::Base
validates :source, allow_blank: true, inclusion: { in:
Source.all.map{ |source| source.name } }
I want to add validation to the property's source to only allow source from sources table.
And then when I run the migration, I got the following error:
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'sources' doesn't exist: SELECT `sources`.* FROM `sources`
The problem is query of source table is occured when it hasn't been initialized yet.
Any tips on how I can get the migration to run?
This is run on production level. so I might can't drop all the migration and rearrange it.
Rails version 4.2.5
SQL version 5.7
Keep in mind that your Source.all.map{ |source| source.name } is going to be executed when the Property class is being loaded. The Source class might not be properly initialized at that point and there might not be a proper database connection set up. Also, you'll only access Source.all once so you'd have to restart your app if you added a new Source.
Instead, validate by hand:
class Property < ActiveRecord::Base
validate :valid_source
private
def valid_source
return if(source.blank?)
return if(Source.where(name: source).exists?)
errors.add(:source, 'Unknown source') # Or whatever you want to say
end
end
That way you're checking the sources table at the right time.
Also, I wouldn't expect the error you're seeing to occur in a migration. Perhaps you're using a model inside a migration, that is to be avoided.
As an aside, is there particular reason that you don't have belongs_to :source instead? Copying the name around like that is very error prone, using a reference (hopefully backed by a foreign key in the database) would be much safer.
Have you defined Source model? I hope so.
Here the problem looks like the loading of Property class takes priority before
migration is run and hence the issue.

Model with namespace - wrong table name (without namespace)

I found a problem in one of legacy applications (outdated rails-3.0.20).
This application has lots of components and nested models. Problem existed only on one of production servers (same environments like other productions and mine dev).
There was model with name space which looks like
module Great
class Item
end
end
Table name was named great_items.
When i debug/open it on server with fault i've found that calculated table name was items istead of great_items.
$ Great::Item.all
#=> ActiveRecord::StatementInvalid: No attribute named `name` exists for table `items`
So i thought mby there is simmilar class with same namespace, I've checked it and it wasn't. My 2nd thought was to set table name explicit i tried
self.table_name = 'great_items'
# &
set_table_name 'great_items'
After this changes i run rails c and table name was setted fine:
$ Great::Item.table_name
#=> 'great_items'
But when i tried to obtain some items there was a freak error, which i could not understand till now!
$ Great::Item.all
#=> ActiveRecord::StatementInvalid: Mysql2::Error: Table 'db.items' doesn't exist: SELECT `great_items`.* FROM `items` WHERE `great_items`.`some_default_scope` = 0
As you can see in above example table has correct name for select values and in where statement, but in from value is incorrect.
I was curious so I've checked ActiveRecord::Base mysql adapter and there was some kind of catching table name so i tried to reset_table_name. Reset helped to setup expected name('great_items') but above errors didn't missed.
Problem dissapeared when i turn of class catching in production enviroment - but it wasn't solution.
Finally I kinda 'solved' this using reset_column_information after set_table_name, but i think it isn't good solution either.
My question is do you know what really could cause this issue and how to solve it without reloading class cache?
Assumed table names dont take into account the modules, as you noticed.
But as you already know, you can set it yourself, using:
self.table_name = 'great_items'
According to this doc, because you use 3.0.x, you have to use:
set_table_name "great_items"
This must be put on top of your class definition
Try this
class RenameOldTableToNewTable< ActiveRecord::Migration
def self.up
rename_table :old_table_name, :new_table_name
end
def self.down
rename_table :new_table_name, :old_table_name
end
end

ActiveRecord not behaving as I expect it

Ruby 2.0
Windows 8.1
Rails 4.1
MySQL2 gem
To avoid an error, I am using the following code to check for an existing payment, prior to creating a new payment record:
payment = {"organization_id" => organization_id,
"date" => row[1],
"amount" => row[2],
"description" => row[3]}
slug = "#{organization_id.to_s}_#{row[1].to_s}_#{row[2].to_s}_#{row[3]})
organization_payment = OrganizationPayment.where(:slug => slug)[0]
if !organization_payment
new_organization_payment = OrganizationPayment.create(payment)
end
Every once in a while, I am getting the following error:
Mysql2::Error at /process_uploaded_payments_data
Duplicate entry 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' for key 'index_organization_payments_on_slug'
I also have the following in my model:
validates_uniqueness_of :slug
Is there any reason why the entry causing the duplicate error would not have been caught by the code above? Any ideas?
Solution
I am still not certain what caused the problem, but I learned the hard way that validating uniqueness does not really work, if you also have a before_save call in your model that creates the slug in question. The workaround is an exception handler:
begin
new_organization_payment = OrganizationPayment.create(payment)
rescue ActiveRecord::RecordNotUnique
next
end
I don't know if this is your problem but a possible cause of this could be race condition -- when your code is running in a process it can be interrupted right after the if condition before it creates the new record.
Putting a unique constraint on the column in the database is a fine way of dealing with this problem, though. You can catch the exception and deal with it that way. You also don't have to manually check for the duplicity, you can use active record validations; fetching the entire record just to check if it exists is not the best practice anyway. More info:
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

Rails unit tests fail because of unique constraint on schema_migrations

I'm trying to run rake test:units and I keep getting this:
Mysql::Error: Duplicate entry '2147483647' for key 1: INSERT INTO `ts_schema_migrations` (version) VALUES ('20081008010000')
The "ts_" is there because I have ActiveRecord::Base.table_name_prefix set. I'm confused because there is no value '20081008010000' already in the table, and there is no migration with the value '2147483647' (though the value does appear in the table).
In Rails' schema_statments.rb, there is the following:
def initialize_schema_migrations_table
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
unless tables.detect { |t| t == sm_table }
create_table(sm_table, :id => false) do |schema_migrations_table|
schema_migrations_table.column :version, :string, :null => false
end
...
In my development database, ts_schema_migrations.version is a VARCHAR. In test, though it's an INTEGER. I've dropped the tables and re-run the migrations (and/or a rake db:schema:load RAILS_ENV=test) several times. No changes.
Is something wrong with my MySQL adapter?
It looks as though your test schema is Rails 1.x somehow, whereas development is Rails 2. Perhaps you could set RAILS_ENV to test and run rake db:reset
It looks like you skipped some steps when upgrading from Rails 1.x to 2.0.
Go through and read the upgrade notes:
http://www.slashdotdash.net/2007/12/03/rails-2-upgrade-notes/
And the release notes:
http://weblog.rubyonrails.org/2007/12/7/rails-2-0-it-s-done
They will tell you all the steps you need to follow. Particularly regenerating all the scripts and migrating your database to the new system of database migrations by timestamp instead of incrementing migration id.