How can I reload the table schema later on?

Given that I have the following migration:

Sequel.migration do up do alter_table :users do add_column :is_admin, :default => false end # Sequel runs a DESCRIBE table statement, when the model is loaded. # At this point, it does not know that users have a is_admin flag. # So it fails. @user = User.find(:email => " admin@fancy-startup.example ") @user.is_admin = true @user.save! end end 

Then the sequel does not automatically reload the table structure (see the comment on the line).

I use this ugly hack to get around it:

 # deep magic begins here. If you remove a single line, it will # break the migration. User.db.schema("users", :reload => true) User.instance_variable_set(:@db_schema, nil) User.columns User.new.respond_to?(:is_admin=) sleep 1 

Is there a better way?

+4
source share
1 answer

Much easier than your hacking this hack: (re) set the dataset to the table name:

 User.set_dataset :users 

In action:

 require 'sequel' DB = Sequel.sqlite DB.create_table :users do primary_key :id String :name end class User < Sequel::Model; end User << { name:"Bob" } DB.alter_table :users do add_column :is_admin, :boolean, default:false end p User.first #=> #<User @values={:id=>1, :name=>"Bob", :is_admin=>false}> p User.setter_methods #=> ["name="] User.set_dataset :users # Make the magic happen p User.setter_methods #=> ["name=", "is_admin="] @user = User.first @user.is_admin = true @user.save p User.first #=> #<User @values={:id=>1, :name=>"Bob", :is_admin=>true}> 

Note that there is no Sequel::Model#save! ; I changed it to save to make it work.

+6
source

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


All Articles