Database and migration question


#1

I have a problem with a project I am working on.

What I would like to know is, is there a way to create a field in a
database dynamically after an action from a user is done. Such that the
user can create a field on the fly and create as many as they want?

The story.

I have an ecom site and we sell products, but the price components (i.e.
tax, cost, markup ect.) are dynamic. The way the company wants it set
up, there are identifiers. The user can make as many identifiers as they
want. An identifier would be tax, cost, markup, or maybe something like
fee. The goal is that I don’t care how many they make, but we need to
save these to the DB. We can make a static number of fields, but if they
make more identifiers then we have to go back manually and run a new
migration. I want to get away from this if at all possible.

If anyone has a better idea, i’m totally down with it. Any help would be
great.

Thanks,

Jeremy


#2

Jeremy W. wrote:

I have a problem with a project I am working on.

What I would like to know is, is there a way to create a field in a
database dynamically after an action from a user is done. Such that the
user can create a field on the fly and create as many as they want?

The story.

I have an ecom site and we sell products, but the price components (i.e.
tax, cost, markup ect.) are dynamic. The way the company wants it set
up, there are identifiers. The user can make as many identifiers as they
want. An identifier would be tax, cost, markup, or maybe something like
fee. The goal is that I don’t care how many they make, but we need to
save these to the DB. We can make a static number of fields, but if they
make more identifiers then we have to go back manually and run a new
migration. I want to get away from this if at all possible.

If anyone has a better idea, i’m totally down with it. Any help would be
great.

Thanks,

Jeremy

This is a classic one-to-many database problem. The solution is to make
a new table (call it something like price_components) and connect it to
your Client table with a foreign key. (I think this is what you want.
I’m not sure from your description whether each client has their own set
of price components or each product does.) Assuming your clients are in
a clients table it might look something like:

create_table ‘price_components’ do |t|
t.column ‘client_id’, :integer, :null=>false
t.column ‘name’, :string # tax,cost, markup, etc…
t.column ‘amount’, :float
end

Then a model for it: app/model/price_component.rb

class PriceComponent < ActiveRecord::Base
belongs_to :client
end

And in your original model: app/model/client.rb

class client < ActiveRecord::Base
has_many :price_components

#rest of the model goes here

end