Reputation: 9307
I have a script using ActiveRecord that creates column names dynamically based on values read from a CSV file, something like this:
FasterCSV.foreach('votes.csv', :headers => true) do |row|
column_name = "roll_call_id_#{row['roll_call_id']}"
if !Legislator.columns.map(&:name).include?(column_name)
connection_pool.connection.add_column('legislators', column_name, 'string')
end
end
The problem is that, after creating the new column, I can't do a legislator.update_attribute(column_name, value)
because the class doesn't pick up the new column and complains it doesn't exist.
How can I make it query the table structure again?
Upvotes: 15
Views: 6228
Reputation: 1
as obvio171 pointed out, it's quite easy:
You need to create a bare model class upfront.
Then in the migration you need to call MyModel.reset_column_information, so that the column information is reloaded so that is up with the new table you just created (or changed)
You can then use just every method to create new records.
I use something like:
data = [[1,'foo'], [2,'bar'],[3,'zip']].map{|a,b| {id:a, txt:b} }
MyModel.create!(data)
But if your seed data is more than a few constants, then you should probably not burry your data into a migration like this.
Upvotes: 0