Reputation: 8284
I have a table called 'products' (model is Product) and I can't access the :uuid attribute when running in migration context. The migration itself does not change the structure but accesses and creates new objects to populate the DB.
This is a snippet of the schema.rb prior to the migration:
create_table "products", force: :cascade do |t|
t.string "title"
t.string "description"
t.string "price"
t.uuid "uuid"
end
The Product object is defined as follows:
class Product < ActiveRecord::Base
end
Now when running in rails console / code this works fine:
p = Product.create!(:uuid => xxx)
puts p.uuid # => xxx
puts p.inspect # => Product(title: string, description: string, price: string, uuid: uuid)
However while running in the migration context - the same code raises an exception:
p = Product.create!(:uuid => xxx)
puts p.uuid # => undefined method `uuid' for <Product:0x007fea6d7aa058>/opt/rubies/2.2.0/lib/ruby/gems/2.2.0/gems/activemodel-4.2.3/lib/active_model/attribute_methods.rb:433
puts p.inspect # => Product(title: string, description: string, price: string)
The uuid attribute is missing! What's wrong?
Upvotes: 1
Views: 540
Reputation: 32933
put
Product.reset_column_information
before your Product.create
line.
Upvotes: 1
Reputation: 176402
The schema of the model is generally refreshed after the migration. Therefore, even if the uuid
field is created, the model doesn't have knowledge of it yet.
You can force a refresh by using
Product.reset_column_information
However, the issue in your code reveals you are probably using the migration feature to create records inside the migration itself. This is generally not recommended as the migrations are designed to change the schema of your database, not the data.
You should use create a specific rake task to modify the data and run the task after the migration is completed, for example from the console.
Upvotes: 1