Trouble with relation in postgresql database migration - ruby-on-rails

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

Related

Rails activeadmin cannot detect auto increment field existing table

I have existing rails app that have some tables with some data. I did the CRUD operation directly from postgresql client before using activeadmin.
I don't know whether I missed the documentation or this is a bug: activeadmin cannot detect my existing autoincrement id for table.
If I refresh the submitted form until the auto increment id surpass the existing id in my table, it works.
First think which I could think of would be that you have passed the id parameter in permit params.
Please check that and if is present then remove it.
Secondly,as mentioned in the post that there are already data in the database so there is a problem with the sequences generated, since they can be only used once.
The solution is to set the sequence for your song_artists.id column to the highest value in the table with a query like this:
SELECT setval('song_artist_id_seq', (SELECT max(id) FROM song_artists));
I am assuming that your sequence name "song_artist_id_seq", table name "song_artist", and column name "id".
To get the sequence name run the below mentioned command:
SELECT pg_get_serial_sequence('tablename', 'columname');
For Resetting the postgres sequences from rails console:
ActiveRecord::Base.connection.tables.each do |t|
ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
Another solution would be to override the save() method in your song_artist class to manually set the song_artist id for new records but is not advisable.

Rails rename the ID column in a model

I'm currently looking at migrating an existing system (written in spaghetti PHP) over to rails. The problem is, it has to run off of a live database. A lot of the ID columns on these different tables aren't named id. For instance, the customers table has an ID column called Customer_ID. Upon looking, I just realised that rails does infact seem to find by the primary key instead of a specific column called id.
Will I face a lot of problems later with the naming of these ID columns, specifically in stuff like relationships?
After v2.3.8, set_primary_key :col_name is deprecated.
self.primary_key = 'col_name' is recommended.
http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html
Change primary key attribute in model by using
set_primary_key :col_name

Is there a way of modyfiong a new Rails model without migrations?

So i'm making a Rails application to learn how to use the framework.
I created a user using:
rails g model User name:string
Then I realized my user also needed another attribute and a relationship with another resource called user_role.
Say my UserRole model is something like:
rails g model userRole roleName:string
So far I've found that I can only achieve the change using a migration, but this is rather inconvenient and unclear to me, since I don't really have any old data, I'm just adjusting my model.
Any advise for a noob?
Migration is extremely helpful. It keeps track of your schema changes. However, if you find that you forgot to add an field immediately after creating migration, you can edit the old migration without creating a new. If you already migrated your database (using rake db:migrate) you can rollback.
rake db:rollback
Now, edit the migration file and add/remove you fields. When completed, migrate again
rake db:migrate
When you create a separate model, you SHOULD create a separate migration. Otherwise, in future you will be confused yourself. btw, when creating children model, you don't need any change in the parent migration. you need to add foreign key in the child table. you can use something like this:
rails g model Comment post:references
this will add post_id in the comment table.
You could try a non-database backed ActiveModel-like model. For example, Mongoid or Datamapper. Many NoSQL solutions don't require migrations for changes to models.
Try this:
rails g model ModelName --migration=false

Rails 3 - using set_primary_key causes routing Error

I was searching google and stackoverflow for long time, but I can't find the solution of my problem.
Lately, I was using set_primary_key for a table called "employee", because I need to use ther personnel number as my primary key. If I set the code
`set_primary_key :personel_number`
(Personel_number is already a collumn which I want to use as primary key) into my model before I do rake db:migrate and do migrating at last, I come into troubles when I try to fill my database via browser:
`Couldn't find employee with ID=1`
`app/controllers/mitarbeiters_controller.rb:16:in `show'`
Rails searches for employee with ID=1 but it can't find, because I set primary key from personel_number with 601 (e.g.).
Can I do something against it or shall I let Rails create it's own :id first?
It sounds like when the page goes to the controller to create the employee you have a redirect to show the new employee and it is using the default id.

Creating a new entry in a table that's not part of my rails project

I have a database that's pre-populated with tables from another project..
How do I access these tables with a rails project and create new entries in them?
Thanks!
If those tables are in the same database as your Rails project, then if they have id column as a primary key (or any other primary key that is integer type) you can just create model for each table and it should work. Of course you need to set_table_name and set_primary_key name.
With this, you should be able to:
MyModel.all
MyModel.build ...
and so on.

Resources