Why is this duplicate column error appearing? - ruby-on-rails

I am trying to add a new column active to my table students.
I ran rails g migration add_active_to_students active:boolean to generate this migration:
class AddActiveToStudents < ActiveRecord::Migration[5.0]
def change
add_column :students, :active, :boolean, default: true
end
end
But when I run rails db:migrate I get this error:
PG::DuplicateColumn: ERROR: column "active" of relation "students" already exists
: ALTER TABLE "students" ADD "active" boolean DEFAULT 't'`
As you can see there is not actually an active column in students:
create_table "students", force: :cascade do |t|
t.integer "club_id"
t.string "email"
t.string "address_line_1"
t.string "address_line_2"
t.string "city"
t.string "state"
t.integer "postcode"
t.string "phone1"
t.string "phone2"
t.string "first_name"
t.string "last_name"
t.date "dob"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "picture"
t.integer "payment_plan_id"
t.string "parent1"
t.string "parent2"
t.string "size"
t.text "notes"
t.index ["club_id"], name: "index_students_on_club_id", using: :btree
end
So why would I be getting this error?

I followed the steps that #demir posted and found that, yes, the column was in the database without being listed in the schema. ALTER TABLE students DROP COLUMN active did not give an error message however it also didn't remove the column.
In the end I removed it by:
Entering the console
rails console
Deleting the column
ActiveRecord::Base.connection.remove_column :students, :active

You may have added it somehow. Have you checked the PG database? Connect to the application database and see if there is an active field.
List databases
\l
Connect database
\c your_app_database_name
List table columns
\d+ students
Check active field, remove it if exist.
ALTER TABLE students DROP COLUMN active

You have this column in your DB, but it wasn't dumped to your schema.rb. Maybe a migration was stopped after it added the column, but before it wrote to schema.rb?
You can remove this column manually, running rails dbconsole and then:
ALTER TABLE students DROP COLUMN active

You can follow the above solutions i.e. drop the column from DB first and then run the migration. Most probably what has happened is, you created and run some migration but later deleted that migration file without doing a db:rollback.
One more option that you can consider is to put a conditional migration like:
class AddActiveToStudents < ActiveRecord::Migration[5.0]
def change
unless column_exists? :students, :active
add_column :students, :active, :boolean, default: true
end
end
end

Related

rails_admin using outdated table names

I have two models connected with a has_and_belongs_to_many association: courses and semesters. rails_admin was only giving me the option to add semesters when creating a course, and not the other way around (and really, it's much more useful to add courses when creating a semester). I made some tweaks the migration:
def change
create_table "courses", force: :cascade do |t|
t.string "department"
t.integer "number"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "semesters", force: :cascade do |t|
t.integer "year"
t.string "season"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "semesters_courses", id: false, force: :cascade do |t|
t.integer "semester_id"
t.integer "course_id"
end
add_index "semesters_courses", ["course_id"], name: "index_semesters_courses_on_course_id"
add_index "semesters_courses", ["semester_id"], name: "index_semesters_courses_on_semester_id"
end
I renamed the intermediary table to semesters_courses from courses_semesters, just for clarity. Not only did this not solve the problem, but now when I try to add a new course, it 500s and tells me:
Could not find table 'courses_semesters'
I know I could make this go away by changing the name back, but I'm not sure where railsadmin is getting that name from (and suspect this to be the source of my problem). I've removed and reinstalled railsadmin, dropped and rewritten the tables, and cleared my browser's cache. When I search my entire project tree for "courses_semesters," I only get results in my error log.
New at Rails dev, so I assume I'm missing some config file somewhere that I need to update, but would love some help on where to find it.
You’re overwriting the join table name.
Option 1 you MUST specify the name of the join table in your models
app/models/course.rb
has_and_belongs_to_many :semesters, join_table: "semesters_courses"
app/models/semester.rb
has_and_belongs_to_many :courses, join_table: "semesters_courses"
Or Option 2 just rename your join table to "courses_semesters" by using migration.
rails g migration rename_courses_semesters
class RenameCoursesSemesters < ActiveRecord::Migration
def self.up
rename_table :semesters_courses, :courses_semesters
end
def self.down
rename_table :courses_semesters, :semesters_courses
end
end
Hope this answers your question.

Rails 4 SQLiteException

I am running into SQLiteException that seems to be causing problem.
Schema.rb
create_table "features", force: :cascade do |t|
t.string "name_key"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "features", ["name_key"], name: "index_features_on_name_key"
create_table "organizations", force: :cascade do |t|
t.string "name"
t.string "code"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "organizations_features", id: false, force: :cascade do |t|
t.integer "organization_id"
t.integer "feature_id"
end
This is current schema and i explicity created table organizations_features(still through migration but a separate migration that references a join table) as otherwise create_join_table would create "features_organizations". In that process, if i run
rake db:drop db:create db:schema:load
I still keep getting the following error even without loading a single record in any tables(i never ran db:seed).
ActiveRecord::StatementInvalid: SQLite3::SQLException: near ")": syntax error: INSERT INTO "organizations_features" () VALUES ()
The other question seem to suggest to make the join table name all singular as in organization_feature, but since we share the schema with other services, it is imperative that we use the same naming conventions.
Note: even i tried to create table using migration "create_join_table" the problem seem to persist"
Update : seeds.rb
organization = Organization.create!(name: 'XYZ', code: 'xyz')
feature = Feature.create!(name_key: 'Some Feature')
user = User.create!(name: "user1",
email: "user#abcd.org",
password: "password123",
password_confirmation: "password123",
profile_id: profile.id)
OrganizationsFeature.create!(feature_id: feature.id, organization_id: organization.id)
where OrganizationsFeature looks like this
class OrganizationsFeature < ActiveRecord::Base
belongs_to :organization
belongs_to :feature
end
I found answer to the question in case if someone else runs into the same issue. The test/fixtures/organizations_features.yml file has null records
one :{}
two: {}
which was causing null records to be inserted into the table. This data is loaded every time and hence insert error.
Having proper data/deleting the file solved the issue.

Add_column migration column order

I use Rails 4, SQLite version 3.8.2 and I would like to add new column to my db.
I create new migration:
rails g migration AddFooToStudents foo:string
so I get then :
class AddFooToStudents < ActiveRecord::Migration
def change
add_column :students, :foo, :string, after: :name
end
end
then I run migration:
rake db:migrate
== 20150803095305 AddFooToStudents: migrating
=================================
-- add_column(:students, :foo, :string, {:after=>:name})
-> 0.0009s
== 20150803095305 AddFooToStudents: migrated (0.0011s)
========================
Everythink seems to be OK, in database has been added foo column but instead of after name column, it has been added at the end of table
ActiveRecord::Schema.define(version: 20150803095305) do
create_table "students", force: :cascade do |t|
t.string "name"
t.string "lastname"
t.integer "age"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "second_name", default: "Untitled"
t.string "foo"
end
end
I completely don't know what I do wrong
You're using the after option, and so you could reasonably expect it to put it after :name.
However, this isn't documented very well (if at all) but the after option only works in some DBMSs (possibly only MySQL).
What i do is add my own sql to do this, after the add_column call, like so:
add_column :students, :foo, :string
ActiveRecord::Base.connection.execute("ALTER table students MODIFY COLUMN foo varchar(255) AFTER name")
Your SQL will need to be DBMS-specific, ie tailored to MySql, PostGresql, SQLite etc.
Well, SQLite does not handle AFTER syntax so in this situation the best solution is leave unchanged order of columns or create new table.

Data migrations for older version of friendly id

I'm migrating a very old app from friendly_id 3.2 to 5.1.
I have a user model which currently has a cached_slug field. I created a new field called just slug. Initially, I thought I could just copy the data over from cached_slug to slug, but I noticed that there's also a whole other table called slugs which looks like this:
create_table "slugs", force: :cascade do |t|
t.string "name", limit: 255
t.integer "sluggable_id"
t.integer "sequence", default: 1, null: false
t.string "sluggable_type", limit: 40
t.string "scope", limit: 255
t.datetime "created_at"
end
Following the directions in the FriendlyID README for the Rails Quickstart, I ran rails generate friendly_id which created this table:
create_table "friendly_id_slugs", force: :cascade do |t|
t.string "slug", null: false
t.integer "sluggable_id", null: false
t.string "sluggable_type", limit: 50
t.string "scope"
t.datetime "created_at"
end
So now I'm all confused about what I need to do to complete migration. I tried creating a new user with the console and the friendly_id_slugs table is still empty, so I'm not sure when or what it's used for.
I have two questions:
1) What is this other table used for
2) What do I need to do to migrate my old slugs to the new table/field so it will continue to work moving forward?
Thanks!
If you don't mind losing the FriendlyId's History records (i.e: the old slugs),
drop the old slug table
in the rails console, run <ModelName>.find_each(&:save) for all friendly_id models.
Step 2 should regenerate new slugs.
Warning: Test before doing this on production servers!
Update: You can also perform step 2 in a migration file
class RegenerateSlugs < ActiveRecord::Migration
def change
# <ModelName>.find_each(&:save)
User.find_each(&:save)
Article.find_each(&:save)
end
end

Id column in schema.rb

Everytimes, I have a column for my event object (event-calendar gem) in my schema.rb file
t.integer "id", :null => false
So of course, every time I want to create an event I have an error "null value in column "id" violates not-null constraint" because of this. I tried this solution ActiveRecord::StatementInvalid: PG::Error: ERROR: null value in column "id" violates not-null constraint but it appears everytimes !!! I would like to know WHY this column appears here, I really don't understand...
Any idea ?
When you created the events model, it sounds like you added an id field. This isn't necessary as rails automatically creates this field. Your event model in your schema should look something like:
create_table "events", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
I would rollback the migration, assuming this is the most recent migration:
rake db:rollback
Then update the migration file and remove the id from the create_table block:
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :name
t.timestamps
end
end
end
Then rerun the migration.

Resources