creating database fields without „nifty generators” rails

60 Views Asked by At

Is there a way in Rails to manipulate database fields and corresponding accessor methods without the „nifty generators” ?

I want users, insofar they are privileged, to be able to manipulate the database structure, that is, at least, to add or delete columns. The privileged user should have the possibility to „Add new” some columns.

Say I have an Object/Table artist and it should “dynamically” receive columns as "date of birth", "has played with", "copies sold"


Not sure if it's a dup. It takes a preliminary decision whether Rails discourages from letting the user do this to begin with or or not. (if that's the case => certainly some noSQL solution)

In pure ruby at least it is easy to dynamically add an attribute to an existing Model/Class like this

Test.class_eval do; attr_accessor "new_attribute"; end

and

Test.new.new_attribute = 2 would return => 2 as expected

In order to create or manipulate a customized input mask / model: can I not manually go the same way the generators go and manually call ActiveRecord::Migration methods like add_column as well as create getter/setter-methods for ORM ?

If yes or no, in both cases, which are they to begin with?

Thanks!

1

There are 1 best solutions below

1
JeffD23 On

I am not aware of any elegant way to allow an Object to dynamically create new columns. This would not be a good application design and would lead massive inefficiency in your database.

You can achieve a similar type of functionality you seek using ActiveRecord associations in Rails. Here's a simple example for your Artist model using a related Attributes table.

class Artist < ActiveRecord::Base
  has_many :attributes
end

class Attribute < ActiveRecord::Base
  belongs_to :artist
end

With this association, you can allow your Artist class to create/edit/destroy Attributes. ActiveRecord will use foreign keys in the database to keep track of the relationship between the two models.

If that doesn't work for you, your next best option is to look into NoSQL databases, such as MongoDB, which allow for much more flexibility in the schema. With NoSQL, you can facilitate the insertion of data without a predefined schema.