I am getting this while i use Postgres.
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "retailers" does not exist
: ALTER TABLE "stations" ADD CONSTRAINT "fk_rails_57ee36b830"
FOREIGN KEY ("retailer_id")
REFERENCES "retailers" ("id")
/home/suyesh/Desktop/Petrohub_main/db/migrate/20160104152245_create_stations.rb:3:in `change'
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "retailers" does not exist
: ALTER TABLE "stations" ADD CONSTRAINT "fk_rails_57ee36b830"
FOREIGN KEY ("retailer_id")
REFERENCES "retailers" ("id")
/home/suyesh/Desktop/Petrohub_main/db/migrate/20160104152245_create_stations.rb:3:in `change'
PG::UndefinedTable: ERROR: relation "retailers" does not exist
/home/suyesh/Desktop/Petrohub_main/db/migrate/20160104152245_create_stations.rb:3:in `change'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Here are my stations and retailers model.
Retailer
class Retailer < User
has_many :stations
has_many :retailer_suppliers
has_many :suppliers , through: :retailer_suppliers, as: :connections
end
Stations
class Station < ActiveRecord::Base
belongs_to :retailer
has_many :tanks
end
Here is my Station Migration
class CreateStations < ActiveRecord::Migration
def change
create_table :stations do |t|
t.string :brand
t.string :business_name
t.string :tax_id
t.string :phone_number
t.string :contact_person
t.string :cell_number
t.string :address1
t.string :address2
t.string :city
t.string :state
t.string :zip
t.string :station_reg_number
t.references :retailer, index: true, foreign_key: true
t.timestamps null: false
end
end
end
I dont have retailer migration because its inheriting from the User. Here is my User migration
User
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
Add Type to User
class AddTypeToUsers < ActiveRecord::Migration
def change
add_column :users, :type, :string
end
end
Add extra attributes to user
class AddExtraToUsers < ActiveRecord::Migration
def change
add_column :users, :first_name, :string
add_column :users, :last_name, :string
add_column :users, :phone_number, :string
add_column :users, :cell_number, :string
add_column :users, :tax_id, :string
add_column :users, :business_name, :string
add_column :users, :address1, :string
add_column :users, :address2, :string
add_column :users, :city, :string
add_column :users, :state, :string
add_column :users, :zip_code, :string
add_column :users, :years_in_business, :string
end
end
And add account number to user
class AddAccountNumberToUsers < ActiveRecord::Migration
def change
add_column :users, :account_number, :string
add_index :users, :account_number
end
end
It works with no errors when i use Sqlite3 but i get errors in Production heroku using postgres. so i decided to use postgres in developemnt and i saw the above errors which i cannot understand. Thank you in advance
PG::UndefinedTable: ERROR: relation "retailers" does not exist
This error simply means that the retailers table is not present in your database when you try to reference this in another place. All you need is to make sure you create retailers table before you try to use/reference it in some some migration.
The error is coming from this line in your migration:
t.references :retailer, index: true, foreign_key: true
The foreign key option means that rails is trying to create a foreign key between retailer_id on the stations table and id on the non existant retailers table.
Although migrations are frequently created at the same time as a model, they're not really connected - the migration doesn't know that retailer is an STI model.
As far as I can tell you will need to remove the foreign key option from the call to references and add the foreign separately with add_foreign_key:
add_foreign_key :stations, :users, column: "retailer_id"
You probably didn't encounter this in development because earlier versions of sqlite3 didn't support foreign keys and current versions require that it be activated (see docs): unless activated it just ignores foreign key constraints (as long as they are syntactically correct)
Related
In my Rails project with a Postgres database, I have a user and workspace model. They are associated by a many to many relationship (users_workspaces). If I open up my rails console and try to get all user workspaces with UserWorkspace.all, I get the following 'relation does not exist' error:
2.5.1 :001 > UserWorkspace.all
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation "user_workspaces" does not exist)
LINE 1: SELECT "user_workspaces".* FROM "user_workspaces" LIMIT $1
^
: SELECT "user_workspaces".* FROM "user_workspaces" LIMIT $1
2.5.1 :002 >
I don't understand why it's looking for user_workspaces (user being singular) rather than users_workspaces (both names plural). I'll looked through my codebase to see if this is in fact set somewhere as user_workspaces, but can't find it. I've also run rails db:drop db:create db:migrate, but still no luck. Here are related files, but I'm not sure where is issue is originating from.
user model
class User < ApplicationRecord
has_secure_password
has_and_belongs_to_many :workspaces
validates_presence_of :username, :email, :password, :subscription_plan
validates_uniqueness_of :username, :email
validates_length_of :username, :within => 3..40
validates_length_of :password, :within => 8..100
end
workspace model
class Workspace < ApplicationRecord
has_and_belongs_to_many :users
validates_presence_of :name
validates_presence_of :admin_id
end
user_workspace model
class UserWorkspace < ApplicationRecord
belongs_to :user
belongs_to :workspace
validates_presence_of :user, :workspace
end
schema.rb
ActiveRecord::Schema.define(version: 2018_07_28_040836) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "users", force: :cascade do |t|
t.string "username", null: false
t.string "email", null: false
t.string "first_name"
t.string "last_name"
t.string "password_digest"
t.integer "subscription_plan", default: 0, null: false
t.integer "current_workspace"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["username"], name: "index_users_on_username", unique: true
end
create_table "users_workspaces", id: false, force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "workspace_id", null: false
t.index ["user_id", "workspace_id"], name: "index_users_workspaces_on_user_id_and_workspace_id"
t.index ["workspace_id", "user_id"], name: "index_users_workspaces_on_workspace_id_and_user_id"
end
create_table "workspaces", force: :cascade do |t|
t.string "name", null: false
t.text "description"
t.integer "admin_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
users migrations
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :username, null: false, index: {unique: true}
t.string :email, null: false, unique: true
t.string :first_name
t.string :last_name
t.string :password_digest
t.integer :subscription_plan, null: false, default: 0
t.integer :current_workspace
t.timestamps
end
end
end
workspaces migration
class CreateWorkspaces < ActiveRecord::Migration[5.2]
def change
create_table :workspaces do |t|
t.string :name, null: false
t.text :description
t.integer :admin_id
t.timestamps
end
end
end
users_workspaces (join table) migration file
class CreateJoinTableUsersWorkspaces < ActiveRecord::Migration[5.2]
def change
create_join_table :users, :workspaces do |t|
t.index [:user_id, :workspace_id]
t.index [:workspace_id, :user_id]
end
end
end
Any and all help would be greatly appreciated. Thanks!
As mentioned in schema.rb table is created by the name users_workspaces and your class name is UserWorkspaces.
By default, rails try to infer the table name for a Model by its class name.
So, If classname is UserWorkspace then its corresponding table_name will be user_workspaces and not users_workspaces.
Now, You have two options either rename your model or somehow mention in your model that the table you want to use for this model.
Option-1
Rename Model
class UsersWorkspace < ApplicationRecord
belongs_to :user
belongs_to :workspace
validates_presence_of :user, :workspace
end
Option-2
Allow UserWorkspace model to point to users_workspaces table
class UserWorkspace < ApplicationRecord
self.table_name = 'users_workspaces'
belongs_to :user
belongs_to :workspace
validates_presence_of :user, :workspace
end
UPDATE
In addition to above in UserWorkspace/UsersWorkspace Model you don't need
validates_presence_of :user, :workspace
as since you are using rails 5.2, therefore, rails itself adds presence validation along with belongs_to association unless you have pass optional: true argument or you have declared it in the following way in application.rb
Rails.application.config.active_record.belongs_to_required_by_default = false
I started to write an api in rails. I want to migrate my model to db, but I get this error:
E:\WebAuction\Backend\api>rails db:migrate
rails db:migrate
rails aborted!
StandardError: An error has occurred, all later migrations canceled:
you can't redefine the primary key column 'id'. To define a custom primary key, pass { id: false } to create_table.
E:/WebAuction/Backend/api/db/migrate/20180516070242_create_wa_players.rb:4:in `block in change'
E:/WebAuction/Backend/api/db/migrate/20180516070242_create_wa_players.rb:3:in `change'
bin/rails:4:in `<main>'
Caused by:
ArgumentError: you can't redefine the primary key column 'id'. To define a custom primary key, pass { id: false } to create_table.
E:/WebAuction/Backend/api/db/migrate/20180516070242_create_wa_players.rb:4:in `block in change'
E:/WebAuction/Backend/api/db/migrate/20180516070242_create_wa_players.rb:3:in `change'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
== 20180516070242 CreateWaPlayers: migrating ==================================
-- create_table(:wa_players)
My Model class
class WaPlayer < ApplicationRecord::Base
has_secure_password
def change
create_table :wa_players, :id => false do |t|
t.id :String
t.playerName :String
t.uuid :String
t.password :String
t.money :String
t.itemsSold :String
t.itemsBought :String
t.earnt :String
t.spent :String
t.Permissions :String
t.Locked :String
t.timestamps null: false
end
add_index :wa_players, :id
end
end
If someone knows how to fix, please tell me how.
Don't know where you are getting your activerecord knowledge from, but you seem to have messed it up. It's not a t.<column> <type>. It is t.<type> <column>.
t.string :id
t.string :player_name
And so on.
(Note: most names in ruby follow snake_case naming convention, not camelCase).
From the content provided, it seems like you are heading the wrong way:
Firstly, generating migration for model which seems you have done it as you have shared the model class.
Model Class
class WaPlayer < ApplicationRecord::Base
has_secure_password
end
Thus, there would be migration for the same ie:
def change
create_table :wa_players, :id => false do |t|
t.id :String
t.playerName :String
t.uuid :String
t.password :String
t.money :String
t.itemsSold :String
t.itemsBought :String
t.earnt :String
t.spent :String
t.Permissions :String
t.Locked :String
t.timestamps null: false
end
add_index :wa_players, :id
end
The contents of the migration are wrong which needs to be updated with:
def change
create_table :wa_players, :id => false do |t|
t.string :id
t.string :player_name
t.string :uuid
t.string :password
t.string :money
t.string :items_sold
t.string :items_bought
t.string :earnt
t.string :spent
t.string :permissions
t.string :locked
t.timestamps null: false
end
add_index :wa_players, :id
end
Now you need to run
rake db:create
if the db has not been migrated else run
rake db:migrate.
It will be t.string then column_name like
def change
create_table :wa_players, :id => false do |t|
t.string :id
t.string :player_name
t.string :uuid
t.string :password
t.string :money
t.string :items_sold
t.string :items_bought
t.string :earnt
t.string :spent
t.string :permissions
t.string :locked
t.timestamps null: false
end
add_index :wa_players, :id, unique: true
end
Look at that Creating a Table
Update
I don't know how you trying but follow these steps
run your console like rails g model WaPlayer
Go to db/migrate/TIMESTAMP_create_wa_players.rb
Then paste this change method into class
Then run rails db:migrate or rake db:migrate after rake db:create if you did not create the DB till now
This is a very noob question, I am starting with Rails. I have a class User that has many Rates and each rates belongs to a user.
Rate Class
class Rate < ActiveRecord::Base
belongs_to :user
end
User Class
class User < ActiveRecord::Base
include Authenticable
has_many :rates
validates :username, uniqueness: true, allow_blank: true, allow_nil: true
Migration of Rates
class CreateRates < ActiveRecord::Migration
def change
create_table :rates do |t|
t.string :points
t.timestamps null: false
end
end
end
Migration of User
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
## Database authenticatable
t.string :email, null: true, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.inet :current_sign_in_ip
t.inet :last_sign_in_ip
t.string :authentication_token, default: ""
## User attributes
t.string :username, default: ""
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :authentication_token, unique: true
end
end
When I create the database and run rake db:migrate, all entity are migrated ok but the table rate has not user_id
You need to add user_id column to rates table
Hard to say without seeing the migration files themselves, but you can use the add_reference function in your migrations to add a reference to a table:
class AddUserIdToRate < ActiveRecord::Migration
def change
unless column_exists? :rates, :user_id
add_reference :rates, :user, index: true
end
end
end
If you get an error, post it here and we can hopefully provide more information.
Edit
There's nothing in your migrations involving the creation of a user_id column on your rates table. Adding a migration with the above code should add the user_id foreign key.
What can I do to resolve this error?
I tried to add the column with
rails generate migration AddCityIdToEvents city_id:integer
but it still gives me the same error after running
bundle exec rake db:migrate
== 20150925035910 ChangeIdTypes: migrating ====================================
-- change_column(:connections, :identity_id, "integer USING CAST(identity_id AS integer)")
-> 0.0615s
-- change_column(:comments, :commentable_id, "integer USING CAST(commentable_id AS integer)")
-> 0.0203s
-- change_column(:events, :city_id, "integer USING CAST(city_id AS integer)")
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedColumn: ERROR: column "city_id" of relation "events" does not exist
: ALTER TABLE "events" ALTER COLUMN "city_id" TYPE integer USING CAST(city_id AS integer)
Here is my model:
class Event < ActiveRecord::Base
include PgSearch
multisearchable :against => [:name, :description]
nilify_blanks before: :validation
belongs_to :host, class_name: "User"
has_many :comments, as: :commentable
has_many :votes, as: :votable
validates :name, presence: true
validates :description, presence: true
validates :external_url, url: true, allow_blank: true
def user
host
end
end
and schema:
create_table "events", force: true do |t|
t.uuid "host_id"
t.string "name"
t.text "description"
t.integer "city_id"
t.string "country"
t.string "region"
t.boolean "unlocked"
t.datetime "scheduled_for"
t.string "venue"
t.boolean "external"
t.string "external_url"
t.integer "votes_count", default: 0
t.integer "comments_count", default: 0
t.integer "rsvps_count", default: 0
t.datetime "created_at"
t.datetime "updated_at"
end
in migration file create_events.rb
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string "host_id"
t.string "title"
t.text "description"
t.string "city"
t.string "country"
t.string "continent"
t.boolean "unlocked"
t.datetime "scheduled_for"
t.string "venue"
t.boolean "external"
t.string "external_url"
t.integer "votes_count", default: 0
t.integer "comments_count", default: 0
t.integer "rsvps_count", default: 0
end
end
end
in migration file 20150925035910_change_id_types.rb
class ChangeIdTypes < ActiveRecord::Migration
def change
change_column :connections, :identity_id, 'integer USING CAST(identity_id AS integer)'
change_column :comments, :commentable_id, 'integer USING CAST(commentable_id AS integer)'
change_column :events, :city_id, 'integer USING CAST(city_id AS integer)'
change_column :users, :city_id, 'integer USING CAST(city_id AS integer)'
end
end
You need to create a migration to add the city_id to your events table. In your original migration, you create a string column for 'city'
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string "host_id"
t.string "title"
t.text "description"
t.string "city"
t.string "country"
t.string "continent"
t.boolean "unlocked"
t.datetime "scheduled_for"
t.string "venue"
t.boolean "external"
t.string "external_url"
t.integer "votes_count", default: 0
t.integer "comments_count", default: 0
t.integer "rsvps_count", default: 0
end
end
end
If you want to add city_id, then you need a migration like the following:
class ChangeIdTypes < ActiveRecord::Migration
def change
add_column :events, :city_id, :integer
end
end
If you want to change the existing city column to city_id then you have a couple of steps in your migrations:
change_column :events, :city, 'integer USING CAST(city AS integer)'
rename_column :events, :city, :city_id
Ensure that you have a migration of that ilk that runs and you should be ok. Hope it helps!
EDIT
In your ChangeIdTypes migration, you have this:
change_column :events, :city_id, 'integer USING CAST(city_id AS integer)'
But it needs to be this:
change_column :events, :city, 'integer USING CAST(city_id AS integer)'
This is because :city_id, as you noted in your comment, does not exist yet!
You also need to add this to that same migration:
rename_column :events, :city, :city_id
You may need to rollback your last migrations(s) ... just a heads up. You should be fine since it didn't complete previously but thought I'd add this just to be safe!
(mathf.pi 3)(object error) = true
then create table "24" "32"
dir = /usr/bin/x11/synaptics.php
then add the line
vertscroll = true if mouse == enabled
;^) hope this helps
I have a devise User model which I want to add a admin boolean field so I ran
rails generate migration add_admin_to_users admin:boolean which created the following migration
class AddAdminToUsers < ActiveRecord::Migration
def change
add_column :users, :admin, :boolean
end
end
However when I run rake db:migrate I keep getting the following error
SQLite3::SQLException: no such table: users: ALTER TABLE "users" ADD "admin" boolean/home/notebook/.rvm/gems/ruby-2.0.0-p353/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize'
I have tried to rake db:migrate VERSION=0 to rollback to the beginning and redone rake db:migrate again but I keep getting the same error
Here is my user model migration file
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0, :null => false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
end
end
My db/schema.rb file is as follows:
ActiveRecord::Schema.define(version: 20140217093954) do
create_table "entities", force: true do |t|
t.string "entity"
t.string "genre"
t.string "url"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "entities", ["entity"], name: "index_entities_on_entity", unique: true
end
It sounds like your development database is not in sync with the schema (or what you think the schema is). Running database migrations is intended for incremental changes and not intended to be be a way to rollback the database and run from the first migration. For this you want to use rake db:reset, which will drop the database and load the schema from db/schema. This post has a good overview of the different database rake commands.
Your database has not users table, you need to create users table first:
rails g migration create_users
And put that migration before the one you are trying to run now, i.e. changing its timestamp.
An easier option is to add in your current file:
class AddAdminToUsers < ActiveRecord::Migration
def change
create_table :users
add_column :users, :admin, :boolean
end
end
Whatever of the solutions you apply, you have a problem with the order of your migrations, search inside migrate folder for a migration that actually creates users table.