How to create a Database Table in a Controller

I need to create a database table in a controller method, but I get a
undefined method `create_table’ error. so, how to to mixin the methods
that will be needed for creating a table?

Hello!

Unfortunately, you won’t be able to use a mixin to access the methods
that you want to actually create the database table. The create_table
method can only be accessed through classes that inherit
ActiveRecord::Migration.

I would suggest creating another class that inherits
ActiveRecord::Migration and then setup some methods to set all of the
attributes of the table. Once you’ve set that up then you can call
the migrate method of the class and it will update the database.

In controller

class TableController < ApplicationController
def create
@results = CreateUsers.migrate(:up)
end

class CreateUsers < ActiveRecord::Migration
def self.up
create_table …
end

def self.down
  drop_table ....
end

end
end

Now if you’re managing your database using migrations, I would not
recommend updating the database inside the controller unless you save
the migration to the filesystem and manage the versioning on the
schema_info table.

Hope this helps.

On Apr 17, 10:50 am, Nanyang Z. [email protected]

rimas.silkaitis wrote:

In controller

class TableController < ApplicationController
def create
@results = CreateUsers.migrate(:up)
end

what does “CreateUsers.migrate(:up)” mean?

I want to create a table, and the columns of this table will depend on a
hash. This hash includes column name and column type information. Can I
pass this hash to the CreateUsers.migrate(:up) method?

class CreateUsers < ActiveRecord::Migration
def self.up
create_table …
end

I mean I don’t know where to put arguments for a method call like
CreateUsers.migrate(:up).

and why call CreateUsers.migrate(:up), not CreateUsers.up?