Explicitly Set Table Name
ActiveRecord includes a table_name
method that infers your database table name based on a class name. For an empty model called AlternativePost
, here's what it comes up with:
[0] > AlternativePost.table_name
=> "alternative_posts"
If this isn't right, you're in trouble (Postgres example):
[1] > AlternativePost.new
PG::UndefinedTable: ERROR: relation "alternative_posts" does not exist
Luckily, you can set the table name explicitly with the table_name=
method.
class AlternativePost < ActiveRecord::Base
self.table_name = 'posts'
end
Now Rails knows which database table to refer to:
[2] > AlternativePost.table_name
=> "posts"
[3] > AlternativePost.new
=> #<AlternativePost:0x007f8554dcbd98 id: nil, title: nil...
A practical application would be a model Post
that corresponds to a table organized inside a Postgres schema admin.posts
.