Search code examples
ruby-on-railsactiverecord

How to define schema for an ActiveRecord model?


I can find how to define columns only when doing migrations.

However i do not need to migrate my model.

I want to work with it "virtually".

Does AR read columns data only from db?

Any way to define columns like in DataMapper?

class Post
  include DataMapper::Resource

  property :id,        Serial 
  property :title,     String
  property :published, Boolean
end

Now i can play with my model without migrations/connections.


Solution

  • In Rails, you need not define properties on your models. They will reflect from the database. Just make sure that you create models for the tables that you want to use. You will, however, need to tell ActiveRecord how to create the relations between models. For information on creating relationships, check this out: http://guides.rubyonrails.org/association_basics.html.

    If you don't use the Rails convention of id for primary keys, you can set the primary key via set_primary_key :your_key (although this is being deprecated). If you do not follow Rails' convention for naming tables, i.e. lowercased, snake-cased, pluralized table names, you can change that via set_table_name 'your_table'.