0

I have a table named "tables" and inside there is a column named table_name. And, on my DB inside other schema I have this table. Like:

db: tables
id  table_name  other_attributes
 1  minerals    ...
 2  animals     ...

db: minerals
id  name  type
 1  rock  nil
 2  sand  nil

The tables doesn't have the same structure. I would like to call my model like:

> tab = Table.find(1)
> tab.elements.all
=> [ {id: 1, name: 'rock', type: nil}, {id: 2, name: 'sand', type: nil} ]

And use any kind of active record tasks inside this .elements... I didn't find any way and the closest article that I found was this: Rails 3/ActiveRecord: How to switch/change table name during request dynamically?

1
  • Just my 2 cents, if you can't figure out how to do this the "railsy" way. You could always ActiveRecord::Base.connection.execute("SQL query") to just create the tables with manual SQL queries. Commented Jan 13, 2014 at 21:56

3 Answers 3

1

I believe the best approach in your case it to perform a direct update to the database. If you don't like to write SQL directly, you can rely on some high-level libraries such as Sequel that in this case are a little bit less coupled to the conventions imposed by ActiveRecord.

Sign up to request clarification or add additional context in comments.

1 Comment

I have no problems writing SQL directly, but as Andrew Wei said, I would like to do it "railsy" way! :) I will study this Sequel.
0

If you are using PostgreSql you might be interested in hstore - http://railscasts.com/episodes/345-hstore. Using hstore (it stores json) would simplify very much your db and application :)

Comments

0

Some time after this question I think (just think because I dont know if it is really right) here is the answer:

class TableMaster < ActiverRecord::Base
  attr_accessor :db
  after_find do
    me = self
    me.db = Class.new ( ActiveRecord::Base ) do
        self.table_name = "schema." + me.tablename
    end
    true
  end
end

Just put it inside the model and there will be a full functional Active Record model inside another. I'm really happy that I got this answer but am still in doubt if it's really right. Please send me some sugestions of it.

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.