How can I get around the model name inside the migration?

The Rails migration guide offers you to create an artificial model within the migration if you need to work with data from a database, for example:

class AddFuzzToProduct < ActiveRecord::Migration class Product < ActiveRecord::Base end def change add_column :products, :fuzz, :string Product.reset_column_information Product.all.each do |product| product.update_attributes!(:fuzz => 'fuzzy') end end end 

The fact is that inside the AddFuzzToProduct class, the product model name will be AddFuzzToProduct::Product . I have the following situation:

 class RemoveFirstNameFromStudentProfile < ActiveRecord::Migration class StudentProfile < ActiveRecord::Base has_one :user,:as => :profile end class User < ActiveRecord::Base belongs_to :profile,:polymorphic => true,:dependent => :destroy end def up StudentProfile.all.each do |student| # I need to do some work on the user object as well as on the student object user = student.user ... # do some stuff on the user object end end end 

The fact is that inside the each block for the student profile, the user is zero. After I activated the registrar, I see that Rails is trying to execute the following request:

  RemoveFirstNameFromStudentProfile::User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."profile_id" = 30 AND "users"."profile_type" = 'RemoveFirstNameFromStudentProfile::StudentProfile' LIMIT 1 

Of course, this can be eliminated by moving User and StudentProfile to the same level, for example, in:

  class StudentProfile < ActiveRecord::Base has_one :user,:as => :profile end class User < ActiveRecord::Base belongs_to :profile,:polymorphic => true,:dependent => :destroy end class RemoveFirstNameFromStudentProfile < ActiveRecord::Migration def up StudentProfile.all.each do |student| ... end end end 

My question is: can moving the definitions of fake models beyond the migration declaration cause any problems for me? Is something missing here? Why did the guys from the Rails team declare them in the migration class?

+4
source share
2 answers

No, this will not cause any problems, since you are not adding new columns or updating them.

The Rails team declared it inside the migration because they added a new column and then updated it, but if the model is outside, and it tries to check this column, which is impossible, since it was not there, it was just added to the migration. For this reason, they created local models in the migration just to become more familiar with it. Using models in your migrations

+1
source

With Ruby, you can always refer to a class or module as the top level, its prefix :: .

An example migration will look like this:

 class AddFuzzToProduct < ActiveRecord::Migration class ::Product < ActiveRecord::Base end ... end 
+2
source

Source: https://habr.com/ru/post/1435927/


All Articles