Forum: Ruby on Rails How to create a Database Table in a Controller

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nanyang Z. (Guest)
on 2007-04-17 19:50
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?
rimas.silkaitis (Guest)
on 2007-04-17 23:45
(Received via mailing list)
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. <removed_email_address@domain.invalid>
Nanyang Z. (Guest)
on 2007-04-18 00:42
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
>     ...
Nanyang Z. (Guest)
on 2007-04-18 00:52
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?
This topic is locked and can not be replied to.