hak8or
hak8or

Reputation: 528

How to add a new column correctly within a rails application without relying on migrations?

Lets say user Bob wants to keep track of his meals calories every day, which are currently breakfast, lunch, dinner, and a snack. So I make a table within rails containing four columns (breakfast, lunch, dinner, snack), and Bob puts in the calories per meal every day with no issues. A few days later, Bob decides he wants to include brunch, so my first thought would be to just write a new migration to add in the brunch column, which is fine if this is a very small scale application and such changes happen rarely, but what do I do if the app will be used by multiple people, with each person wanting to add in their own food time name?

Surely migrations are not the way, as that would require a dev to step in and modify the rails application every time, which could be many times per day. So, is there a way to do this within a rails application, is this a limitation of activerecord, or is this not the way it should be done?

Upvotes: 0

Views: 99

Answers (1)

Bachan Smruty
Bachan Smruty

Reputation: 5734

For that you can add a new table e.g. "lookup_food_types" having column id and food_type. I am assuming that you are keeping the calories in a table which named as "calories". Now in calories table you need to have some modification. Its columns will be "id, user_id, lookup_food_type_id".

So in your LookupFoodType model,

attr_accessible :food_ype
has_many :calories

And in your Calory model,

attr_accessible :user_id, :lookup_food_type_id
belongs_to :lookup_food_type

In the lookup_food_types table you need to add some record initially just like

 id food_type
-----------------
 1  breakfast
 2  lunch
 3  dinner
 4  snack

Now this is your basic food type for every users. If user wants to add a new food type beside the basic food_types, then you can add a new column in the calories table named as 'custom_food_type'

And in the form where user is going to add the calory, you need to show the calory as input and food_type as a select box. And a button, if user wants to add his own food type. and upon clicking that button the text field for "custom_food_type" will be visible. But the condition is that, for that user should not select any type of food type from the basic list. you can achieve it by using jquery.

Hope it will solve your problem.

Upvotes: 3

Related Questions