Reputation: 5859
I am trying to learn rails Active Record.
Learnt that self.table_name
can be used to rename a table which rails create default.
class Order < ActiveRecord::Base
self.table_name = "ordered"
end
But when I run the migration first time , I still get the orders
table, not the one which I mentioned in the string. What is the mistake done here?
migration:
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.timestamps null: false
end
end
end
Upvotes: 2
Views: 4544
Reputation: 191
As an addition to @richard-peck 's comment, the correct syntax for renaming a table from a migration is:
rename_table
Upvotes: 0
Reputation: 76774
class CreateOrders < ActiveRecord::Migration
def change
create_table :ordered do |t|
t.timestamps null: false
end
end
end
This will create an ordered
table.
If you've already got your orders
table, you can use the following:
$ rails g migration ChangeOrdersToOrdered
#db/migrate/change_orders_to_ordered_______.rb
class ChangeOrdersToOrdered < ActiveRecord::Migration
rename_name :orders, :ordered
end
$ rake db:migrate
Tables != Classes
You have to remember that your migrations are not the same as your classes - they are mutually exclusive.
Although the naming conventions are similar, and Rails does a great job of linking the two, the fact remains that you can call your tables whatever you want -- it will have no bearing on your models unless you specifically designate the table tied to the model.
Setting self.table_name
only sets the class that model will read (it's a class method):
Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy looks like:
Reply < Message < ActiveRecord::Base
, thenMessage
is used to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class inActive Support
, which knows almost all common English inflections. You can add new inflections inconfig/initializers/inflections.rb
.
This means that no matter what you refer to in your self.table_name
, you are open to use whichever migrations you want.
Upvotes: 3