Rails 4 SQLiteException - ruby-on-rails

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.

Related

Why is this duplicate column error appearing?

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

rails migration generating random tables. Where is this coming from?

When I run rails db:migrate without a new migration it seems to have added two new tables: questions and questions_1.
In my schema file I see:
create_table "questions", id: false, force: :cascade do |t|
t.integer "id"
t.text "text"
t.boolean "active"
t.integer "organization_id"
t.datetime "created_at"
t.datetime "updated_at"
t.bigint "account_id"
t.bigint "team_id"
end
create_table "questions_1", id: false, force: :cascade do |t|
t.integer "id"
t.text "text"
t.boolean "active"
t.integer "organization_id"
t.datetime "created_at"
t.datetime "updated_at"
t.bigint "account_id"
t.bigint "team_id"
end
I don't have any migrations making these tables. I'm guessing this is some sort of convention. Where do I look to fix this? All recent changes are in the app/ directory and a migration I made has been rolled back and then deleted. Yet when I run rails db:migrate I always get these new tables.
Any ideas?
Rails won't create tables with any name other than the ones specified in a migration. If the table already exists then it will throw an error.
I believe someone has run a migration creating the second table on your database, and then deleted the migration. When rails creates your schema.rb file, it uses your database rather than any migrations, meaning this file reflects your actual database state rather than the one your migrations suggest would be the case.
If you're sure you don't want the second table and it has no data in it, then you can write out a new migration to delete this table, run it, and then delete it. This will return your database state to the one your migrations suggest would be the case. You can then run rake db:schema:dump to update your schema.

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.

Seeding a rails model with an array in rails

I understand that the answer may be in similar answers that I've read but I do not yet have the knowledge power to draw a solution from them.
I'm trying to seed a column in a rails model with an array:
["N1", "N2", "N3", "N4", "N5", etc ]
Each value will represent a new line (or entry? not sure of the correct terminology) in the database column.
Currently, similar to what has been suggested in a similar posts, I'm using:
[above array].each do |pc|
Postcodes.create!({ pcode => pc})
end
But I'm getting the following error:
NameError: uninitialized constant Postcodes
I've tried un-pluralising the model name and also un-capitalising but this does not seem to help.
db:schema:
ActiveRecord::Schema.define(version: 20151211095938) do
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
Model:
class Postcode < ActiveRecord::Base
end
Your model is names Postcode, not Postcodes (not the plural s). The following should work:
codes = ["N1", "N2", "N3", "N4", "N5"]
codes.each do |code|
Postcode.create!(pcode: code)
end

RSpec changing model attribute name

Not the value, the name of the attribute. Yes, for real. I don't know what the hell is going on.
The migration:
class CreateFolders < ActiveRecord::Migration
def change
create_table :folders do |t|
t.string :name, null: false
t.timestamps
end
change_table :bookmarks do |t|
t.belongs_to :folder
end
end
end
The Schema:
ActiveRecord::Schema.define(version: 20140424065045) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "bookmarks", force: true do |t|
t.string "name", null: false
t.string "url", null: false
t.datetime "created_at"
t.datetime "updated_at"
t.integer "folder_id"
end
create_table "folders", force: true do |t|
t.string "name", null: false
t.datetime "created_at"
t.datetime "updated_at"
end
end
What it shows inside of rails c:
[3] pry(main)> Bookmark
=> Bookmark(id: integer, name: string, url: string, created_at: datetime, updated_at: datetime, folder_id: integer)
And now, our huge glaring problem:
[3] pry(#<RSpec::Core::ExampleGroup::Nested_2::Nested_1>)> Bookmark
=> Bookmark(id: integer, name: string, url: string, created_at: datetime, updated_at: datetime, folders_id: integer)
Notice the name of the last attribute there: folders_id
Does anyone know what in the hell could ever cause this?
Finally found what the issue was, and damn is it bizarre.
So brand new in Rails 4, is ActiveRecord::Migration.maintain_test_schema!. This convenient little tool is pretty nice, however it only updates the test schema on creation of a new migration. In the process, if you get a migration wrong the first time, and update it later, you'll find inconsistencies like this.
To fix the problem, run rake db:test:prepare. You'll get a deprecation warning, but ignore it. When you check inside of rspec again it should work fine.

Resources