简体   繁体   中英

How do I run rails g model / rake db:migrate within my rails application

I would like to run "rails g model" and / or "rake db:migrate" within my rails application. When I do it , The "rails g model" works fine, but take long, and "rake db:migrate" raised an error

SQLite3::BusyException: database is locked

The error occurs only when I use after_create and after_save , but works fine when I use before_create or around_create .

My model :

class Table < AbstractModel

     after_create :create_table

     protected

     def create_table
         system("rails g model #{self.name}")
         system("rake db:migrate")
     end

end

Rails generators are not intended to be run from within a Rails application. They're not even really necessary. They're just nice-to-haves. So instead of making a file named Table, you can run rails g model table <attrs> and it will generate the file table.rb in the models and generate your migration with whatever attrs you pass it.

Migrations also, should not be run within the application code. You pretty much have to manage them manually or with a deploy script.

As an aside, after_create is a callback for individual instances of Table . So when you call Table.create({<attrs>}) it would call create_table , which is not what what you want.

EDIT:

Using after_commit not after_create seemed to solve the OP's problem.

What are you trying to accomplish?. As said by evanbikes, the way you have set up is that every time you create an instance of table, you are going to generate a new model. You could run rake tasks on a schedule using cron jobs. If you are using heroku you can use heroic scheduler. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM