self.table_name 不工作
self.table_name is not working
我正在尝试学习 rails Active Record。
了解到 self.table_name
可用于重命名 table,rails 创建默认值。
class Order < ActiveRecord::Base
self.table_name = "ordered"
end
但是当我第一次 运行 迁移时,我仍然得到 orders
table,而不是我在字符串中提到的那个。这里犯了什么错误?
迁移:
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.timestamps null: false
end
end
end
class CreateOrders < ActiveRecord::Migration
def change
create_table :ordered do |t|
t.timestamps null: false
end
end
end
这将创建一个 ordered
table。
如果您已经有了 orders
table,您可以使用以下方法:
$ rails g migration ChangeOrdersToOrdered
#db/migrate/change_orders_to_ordered_______.rb
class ChangeOrdersToOrdered < ActiveRecord::Migration
rename_name :orders, :ordered
end
$ rake db:migrate
表 != 类
您必须记住,您的 迁移 与您的 classes 不同 - 它们是互斥的。
尽管命名约定相似,并且 Rails 很好地连接了两者,但事实是您可以随意调用 table——它不会与您的模型有关除非您特别指定table绑定到模型。
设置 self.table_name
仅设置模型将 读取 的 class(这是一个 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
, then Message
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 in Active Support
, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb
.
这意味着无论您在 self.table_name
中提到什么,您都可以使用任何您想要的迁移。
我正在尝试学习 rails Active Record。
了解到 self.table_name
可用于重命名 table,rails 创建默认值。
class Order < ActiveRecord::Base
self.table_name = "ordered"
end
但是当我第一次 运行 迁移时,我仍然得到 orders
table,而不是我在字符串中提到的那个。这里犯了什么错误?
迁移:
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.timestamps null: false
end
end
end
class CreateOrders < ActiveRecord::Migration
def change
create_table :ordered do |t|
t.timestamps null: false
end
end
end
这将创建一个 ordered
table。
如果您已经有了 orders
table,您可以使用以下方法:
$ rails g migration ChangeOrdersToOrdered
#db/migrate/change_orders_to_ordered_______.rb
class ChangeOrdersToOrdered < ActiveRecord::Migration
rename_name :orders, :ordered
end
$ rake db:migrate
表 != 类
您必须记住,您的 迁移 与您的 classes 不同 - 它们是互斥的。
尽管命名约定相似,并且 Rails 很好地连接了两者,但事实是您可以随意调用 table——它不会与您的模型有关除非您特别指定table绑定到模型。
设置 self.table_name
仅设置模型将 读取 的 class(这是一个 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
.
这意味着无论您在 self.table_name
中提到什么,您都可以使用任何您想要的迁移。