1

I have the following model:

class Product < ActiveRecord::Base

end

How can I add a field to it?

potashin
  • 44,205
  • 11
  • 83
  • 107
gespinha
  • 7,968
  • 16
  • 57
  • 91
  • Assuming this is Ruby On Rails, you should use migrations : http://stackoverflow.com/questions/17728201/adding-updating-column-in-a-model-using-rubymine – John Jul 21 '15 at 23:35

2 Answers2

2

What is the type of the field you wish to add? If it is a string do it like below:

rails generate migration add_field_to_products field:string

Where 'field' is the name of the field you want to add, so rename accordingly.

Then do in the command line rake db:migrate and after that the field should be in the model.

Also, this question is a duplicate of: Adding a column to an existing table in a Rails migration . There is more discussion of this there if it's still unclear.

Community
  • 1
  • 1
ifma
  • 3,673
  • 4
  • 26
  • 38
  • Shouldn't I write anything on the file directly? Or is this the only way, through the command line? – gespinha Jul 21 '15 at 23:51
  • Well you have the model already, so I assume you already ran the original migration which created the products table. But if you haven't yet ran it yet, then you could just add t.string :field inside the create_table loop. Otherwise yes this is the correct way, this is so your schema will change to reflect the new field. – ifma Jul 21 '15 at 23:56
  • Can't I just add a field to the products table inside the products migration? – gespinha Jul 22 '15 at 00:08
0

You should generate a separate migration with rails g migration [name], where you declare your column:

add_column :products, :[column_name], :[datatype]

Where [column_name] is the name of the column you want to add and [datatype] stands for it's datatype: string, integer and etc.
After that you should run migration with rake db:migrate to add new column to your table.

potashin
  • 44,205
  • 11
  • 83
  • 107