0

In my gem I have Rails generator to build migration. That migration is very simple:

class MigrateGenerator < Rails::Generators::Base
  source_root File.expand_path(File.join(File.dirname(__FILE__), '../generators/templates'))

  def create_migration
    template "migration_template.rb", "db/migrate/create_orders_table.rb"
  end
end

class CreateOrdersTable < ActiveRecord::Migration

  def self.up
    create_table(:my_default_name) do |t|
      #some columns
    end
    #indexes
  end
end

class Order < ActiveRecord::Base
  self.primary_key = :id
  self.table_name = 'my_default_name'
end

My question: Is there any possibility to allow user define own table name? I know that I can easily pass parameter to my generator but how to change defined self.table_name = 'my_default_name'

3
  • where does 'my_default_name' come from? for each user Commented Apr 29, 2015 at 10:03
  • do you want to pass self.table_name to generator as param? Commented Apr 29, 2015 at 10:04
  • my_default_name as the name suggests is defined by myself. So always table name will be my_default_name. I would like to allow user to generate migration with custom name Commented Apr 29, 2015 at 10:14

2 Answers 2

1

Either you need to store a mapping between user_id and the table name or follow a standard pattern based on user_id (eg. "_orders")

self.table_name can be both a string as well as a method.

  1. If you are using a standard pattern:

    self.table_name = "#{current_user.id}_orders"
    

Ensure you are logged in before accessing this model.

  1. If it is random, store the mapping between user id and table name of orders of the user.

    def self.table_name
       "special_" + super
    end 
    
Sign up to request clarification or add additional context in comments.

3 Comments

I don't have any mapping. I don't know anything about user. I would like to allow user when they generate migration to use custom name. But than I need that name in AR class
you need to store the mapping before migration and use option 2 from answer
Maybe I am missing something here, but how current_user(session) is accessible in model?
1

If you want to edit table_name during your migration then you should add a parameter:

argument :table_name, type: :string, default: "my_default_name"

and then use it in migration_template and gsub Order class:

gsub_file 'path to your order.rb', /self.table_name.*/, "self.table_name = #{table_name}"

note that pass to order.rb must be absolute or relative to source_root

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.