Disabling & Setting Up Custom Keys in Ruby ActiveRecord & Sinatra (Phase 3)

Jacob Hocker
3 min readNov 7, 2021

There are many things that troubled me on this project ,because there is little to no documentation on just Ruby with Sinatra. All the things you can google are with Rails, Ruby on Rails, etc. So when I needed something done I had to troubleshoot it myself.

The Problem…

The issue I was having was that every time I seeded my data my one in my one-to-many relationships would change the ID given to them through ActiveRecord.

Although you might say “ Why don’t you just assign them to a variable. Then use that variable.id to access as the foreign key in your many table?”

Well you would be pretty correct in almost any case. However not in my case. The reason I needed to come up with a custom and controlled PRIMARY_KEY is because when I would do the submit/POST on my front end using React.js

it would never grab it as a string & I need it to be posted as an integer .

The Solution

Since I needed this PRIMARY_KEY to be posted as a custom integer so that anytime someone was on my site that when they posted an animal for adoption it would go directly to the shelter_id it belonged to.

There is no real documentation as far as I am aware I found bits and pieces ,and put it all together so you don’t have to!

Go to the migrate file you would like to set your customer PRIMARY_KEY for.

Let me break down whats going on here. After creating the table shelters it is telling it that the VARCHAR id ActiveRecord would automatically assign to be false and that you will give it a custom PRIMARY_KEY .

How do we do that? Glad you asked!

On line 5 above I have set what is going to be my PRIMARY_KEY id integer

You have the ability to make your PRIMARY_KEY to be whatever data type you would like. Now I recommend naming that ID something where if someone else will be looking at your code with out knowing anything about you setting the custom id. Can then look at it and instantly recognize it to be the ID for that data table.

Just one more small step and BOOM! You have yourself your own personal custom PRIMARY_KEY that will assist you on whatever functionality you are trying to accomplish.

The last step is to go the model and create a class method that tells it what the primary key name is.

Once you have the set up you are good to go. Test it out by seeding some data and setting your new custom PRIMARY_KEY id!

In my seed file I am able to set my shelter_id to 1 and that will never change now!

I hope this has assisted you as it would have assisted me! It is not a long process very simple once you know what to do!

Have a wonderful day and don’t forget to tell someone you love them!

--

--

Jacob Hocker

Full Stack Software Engineer | UX/UI Designer | Technical Support Specialist