Error Generating Fixtures. Rails was not able to disable referential integrity - ruby-on-rails

I understand that rails is supposed to disable referential integrity when generating the fixtures. So after a quick Google search, i figured out that the solution to the error following error is to make my postgres user a super user. The error:
WARNING: Rails was not able to disable referential integrity.:00, ETA: 00:00:00
This is most likely caused due to missing permissions.
Rails needs superuser privileges to disable referential integrity.
ActiveRecord::InvalidForeignKey: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "responses" violates foreign key constraint "fk_rails_2ec3339f90"
DETAIL: Key (assessment_id)=(1) is not present in table "assessments".
: INSERT INTO "joe"."responses" ("assessment_id", "user_id", "question_id", "choice_id", "created_at", "updated_at") VALUES (1, 1, 1, 1, '2017-05-08', '2017-05-08')
I thought it would be an easy fix, but my postgres user is already a superuser. I did SHOW is_superuser; and the response was on. I even disabled all of the triggers manually from the command line with the same user using alter table responses disable trigger all;. When I list the postgres users using \du, the attributes show up as Superuser, Create role, Create DB.
I am very confident that my user is a superuser. There must be something else going on here. I am using the apartment gem for multi-tenancy. Help is appreciated. If you need any more code, let me know.

The user specified in config/database.yml - say rails_deploy_user needs to have superuser privileges defined, not the generic postgres user.
psql database_environment
\du; # find psql defined users and roles
ALTER ROLE rails_deploy_user WITH SUPERUSER;

Related

RailsAdmin: ActiveRecord::RecordNotUnique , inserts id when creating user #2972

I seem to be getting a problem when inserting into the users table. I am not sure why, but only that it is getting the current user's id (confirmed by seeding additional user. I know the solution would be to remove adding the id when adding users, but I don't know how and have been trying to find the right file for 30 minutes. I am using MYSQL. The error is below:
ActiveRecord::RecordNotUnique in RailsAdmin::MainController#new
Mysql2::Error: Duplicate entry '1' for key 'PRIMARY': INSERT INTO `users`
Any possible solution to this? I am willing to fix if someone just points me to the right file(s). Thanks!
This is my first answer, so take this with many grains of salt. I've had similar issues in the past when I've messed around with the database directly in SQL and ignored callbacks in my models. Messes up the primary key sequence. Some version of resetting the primary key usually helped. Something like:
https://apidock.com/rails/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter/reset_pk_sequence%21
Should look something like: ActiveRecord::Base.connection.reset_pk_sequence!('users')
That might be for PostgreSQL, however. You might have to find a MySQL way to do it. Hope that helps!

Delete record with nil id in rails console heroku ruby postgres

I used destroy to delete a record remotely in heroku rails console and now it does not show up if I write
MyModel.find_by(email: 'some#email.com')
but it does show up if I write
MyModel.find_by_or_create_by(email: 'some#email.com')
...except the id is nil. I can't figure out how to get rid of this record. I am using postgres and rails 4
When I try to create a new record with the same email via the web ui, it triggers the uniqueness validation for this ghost record...yet I can't remove the ghost record.
When find_or_create_by returns a record with a nil id, that suggests the find part is failing, and then the create part fails too with validation errors. What do you get from MyModel.find_or_create_by(email: 'some#email.com').errors.full_messages? I'm guessing you see the same uniqueness validation error as you're seeing in the web console.
Is your app using a soft-delete approach, e.g. with a gem like acts_as_paranoid or permanent_records? Those gems change the behavior of destroy so that it does not issue a SQL DELETE command but instead sets a deleted_at column. They also hide soft-deleted records, so that may be why find_by isn't giving you anything. If this is what you're doing, you should make sure your uniqueness validation knows to ignore soft-deleted records. How to do that depends on your soft-delete implementation, but you might find some tips here.
You might want to try straight SQL to see what's really in your database, e.g. using the Heroku psql prompt or this Ruby code: MyModel.unscoped.where(email: "some#email.com")
find_or_create_by will look for the record by the given parameters and create it if it can't be found. If there isn't an id field that means it isn't being saved and your problem is already solved.

Creating a Migration for Admin Users

How do I create a migration file which will create a user with the role of "admin"? I've written the following:
rails g migration User
How can I give a role of "admin" to this user?
Migrations may serve two functions:
The manipulation of structure in your database
The manipulation of data in your database
Generally speaking it is best practice to use them for the first, and to try to avoid the second (which may cause issues to an upgrade path down the line).
Your question is unclear regarding whether you're asking to create a User table with a column representing administrative privileges, or if you're trying to add an administrative user to an existing Users table.
If you are trying to create a User table, you will want to do the following:
rails g model users is_administrator:boolean other_column:type
Something along these lines will generate a migration (and matching model) allowing Users to be created, with a column containing what could be treated as administrative privileges.
On the other hand, if you already have a Users table, and are trying to add the ability to distinguish administrators from non-administrators, you would be better suited by something like this:
rails g migration add_is_administrator_to_users is_administrator:boolean
Finally, if you are asking how to add a User to the table Users which already exists and contains the column "is_administrator", I would encourage you to add the following line to db/seeds.rb:
User.create( is_administrator: true, other_column: 'other value' )
And then run the following line in the console
rake db:seed
If this doesn't make sense, I would encourage you to read up in Active Record Migrations, or (in the case that you choose to leverage the third method) Active Record Seeds.
You can have users and admin in same table and add one more column called "role" which will be boolean, which will decide if the current user is admin or not
rails g migration user role:boolean name
if role is false than it is not an admin.

Trouble with relation in postgresql database migration

I'm working through the Rails Crash Course book, and the project is to create a social tumblr style clone. I've created a User model with just a name and id (and already migrated), and now I'm trying to implement the following/subscription style that tumblr does. The book has the following to create a new model and migration:
bin/rails g model Subscription leader:references follower:references
The thought is the leader will the the person followed, and the follower is obviously the follower. Both will reference the id from the User table though.
The problem is with the migration. I get the following:
PG::UndefinedTable: ERROR: relation "leaders" does not exist
: ALTER TABLE "subscriptions" ADD CONSTRAINT "fk_rails_7b4891a3a6"
FOREIGN KEY ("leader_id")
REFERENCES "leaders" ("id")
Plus a bunch of other stuff that looks almost exactly the same.
While I'm assuming that it's throwing an error because no leader table with it's own id exists, is there a way to fix the migration to reference the user.id for each reference, or will I just manually need to create each column?
I think it's a Postgres specific problem. You can bypass it by using:
bin/rails g model Subscription leader_id:integer:index follower_id:integer:index

Rails on heroku: after push, get "PG::UniqueViolation: ERROR: duplicate key value violates unique constraint"

This has been asked several times before (here and here, and more).
Every time I push my rails app to Heroku (for at least the last few months, I'd say), I have to reset my keys using the familiar
ActiveRecord::Base.connection.tables.each { |t| ActiveRecord::Base.connection.reset_pk_sequence!(t) }
incantation. Otherwise I get postgresql failures like this when I try to create new records:
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "users_clients_pkey" DETAIL: Key (id)=(401) already exists. : INSERT INTO "users_clients" ("user_id", "client_id") VALUES (20, 46) RETURNING "id"
(This is an example; it happens on various tables, depending on what the first action is that's done on the app after a push.)
Once I do the reset-keys incantation, it's fine until my next push to heroku... even when my push does not include any migrations.
I'm a little baffled as to why this is happening and what can be done to prevent it.
No, there's no datatable manipulation code in my deployment tasks.
Its happening because the primary key(id) value already exists. Why? Because the primary key sequence in postgres is messed up. without looking at the database or knowing the schema, it difficult to suggest a solution but if your database can affort a downtime of 10-15mins. you can try
If there is just one table which is problem. you can Export all data into new set of table with new names without ID column.
drop existing tables and rename the newly created table to old tables's name.
enable writes to our app again.
But if entire DB is in a mess, then it need something more elaborate but I can't tell without looking the schema.

Resources