简体   繁体   中英

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.

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, ie lowercased, snake-cased, pluralized table names, you can change that via set_table_name 'your_table' .

I found this page when googling how to specify non-public schema for my active record model with psql database.

Example you have public and auth schema. In order to specify your model different schema you can use the following

class AdminUser
  self.table_name = 'auth.admin_user'
end

or you can modify your database.yml with schema_search_path option

default: &default
  adapter: postgresql
  encoding: unicode
  username: postgres
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  schema_search_path: 'public,auth'

then you can use just

class AdminUser
  self.table_name = 'admin_user'
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM