开发者

How to create a new database from within a Rails app?

I'm working on a Rails app that has one database per account. (I know this is a controversial approach in itself, but I'm confident it's the right one in this case.)

I'd like to automate entirely the process of creating a new user account, which means I need to be able create a new database and populate it with some seed data programatically from within a Rails app.

My question, then, is how best to do this? I don't think I can just run migrations from within the app (or, if I can, how?), and just running the straight SQL queries within the app with hardcoded CREA开发者_如何学运维TE TABLE statements seems a really unwieldy way of doing things. What approach should I take, then?

Thanks in advance for your help!

David


This is an approach that my application requires. The app provides a web front-end onto a number of remote embedded devices which in turn monitor sensors. Each embedded device runs a ruby client process which reads a config file to determine its setup. There is a need to be able to add a new sensor type.

The approach I have is that each sensor type has it's own data table, which is written into by every device which has that sensor. So in order to be able to create a new sensor type, I need to be able to set up new tables.

One initial issue is that the remote embedded devices do not have a rails app on them - therefore table name pluralization is a bad plan, as the pluralization rules are not accessible to the remote devices. Therefore I set

ActiveRecord::Base.pluralize_table_names = false

in config/environment.rb

The data on each sensor device type is held in a SensorType model - which has two fields - the sensor name, and the config file contents.

Within the SensorType model class, there are methods for:

  1. Parsing the config file to extract field names and types
  2. Creating a migration to build a new model
  3. Altering a particular field in the DB from a generic string to char(17) as it is a MAC address used for indexing
  4. Altering the new model code to add appropriate belongs_to relationships
  5. Build partial templates for listing the data in the table (a header partial and a line_item partial)

These methods are all bound together by a create_sensor_table method which calls all the above, and performs the appropriate require or load statements to ensure the new model is immediately loaded. This is called from the create method in the SensorTypeController as follows:

  # POST /device_types
  # POST /device_types.xml
  def create
    @sensor_type = SensorType.new(params[:sensor_type])

    respond_to do |format|
      if @sensor_type.save

        @sensor_type.create_sensor_tables

        flash[:notice] = 'SensorType was successfully created.'
        #etc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜