Search code examples
rubyormsequel

Find Model name from Table name (Sequel ORM)


In a ruby script I am running a loop in which I am dynamically getting a table name from a list of tables and have to perform some sort of CRUD operation (mainly insertion) on it. I am using Sequel Orm and have created models for the various tables. How do I find the name of the Model for each table so that I can perform the insertion?

    tables=["table1","table2",'table3",...]
    tables.each do |t|
    #perform insertion on t
    #how to find the model name for table t?
    end

I can use a hash to store the model names for each table or can follow a pattern like converting the first character of each table to uppercase or something like that.

Is there a better way to do this?


Solution

  • What you are asking is not possible in the general case without a brute force search, and even then it is ambiguous, for the simple reason that the following is valid:

    class Foo < Sequel::Model(:table1); end
    class Bar < Sequel::Model(:table1); end
    

    Basically, each model has a related dataset (usually just a simple SELECT * FROM table). However, other models can use the same or similar dataset. So going from model to table is simple, but table to model is not.

    If you've created your own models, the easiest way to handle what you want is to use a hash:

    ModelMap = {}
    ModelMap["table1"] = Model1
    ModelMap["table2"] = Model2
    

    Then you can just do:

    ModelMap[t]
    

    inside that each block to get the model class.