ruby on rails使用现有表进行迁移

时间:2021-03-03 00:16:30

I have this problem. I need to use an existing table on a mysql database. The name of the table is not compatible with RoR conventions and I need to remap the table name and the name of the attributes. I have created a scaffold to visualize on a web page the content of the table but I can't change the mapping. Is there a solution to indicate to RoR the relation between the name of the class and the name of the table in the database? and a solution to indicate the relation between the attribute of the class and field on the table? Thanks.

我有这个问题。我需要在mysql数据库上使用现有的表。表的名称与RoR约定不兼容,我需要重新映射表名和属性的名称。我已经创建了一个脚手架,可以在网页上显示表格的内容,但我无法更改映射。是否有解决方案向RoR指示类的名称与数据库中表的名称之间的关系?和一个解决方案,以指示类的属性和表上的字段之间的关系?谢谢。

2 个解决方案

#1


1  

The table name can be specified using table_name class method.

可以使用table_name类方法指定表名。

For the attributes/column, you need to explicitly specify aliases for the attributes using alias_attribute method. For example, if you have name_of_thing column, but want to treat it as name, then you need something like this in your model:

对于attributes /列,您需要使用alias_attribute方法显式指定属性的别名。例如,如果您有name_of_thing列,但想将其视为名称,那么您需要在模型中使用以下内容:

class CreateUtenti < ActiveRecord::Base
  self.table_name = "another_name"
  alias_attribute :name, :name_of_thing
end

#2


0  

Yes you can pass table name in model like:

是的,您可以在模型中传递表名称,如:

class YourModel < ActiveRecord::Base
  self.table_name = "pass_table_name_here"
end

#1


1  

The table name can be specified using table_name class method.

可以使用table_name类方法指定表名。

For the attributes/column, you need to explicitly specify aliases for the attributes using alias_attribute method. For example, if you have name_of_thing column, but want to treat it as name, then you need something like this in your model:

对于attributes /列,您需要使用alias_attribute方法显式指定属性的别名。例如,如果您有name_of_thing列,但想将其视为名称,那么您需要在模型中使用以下内容:

class CreateUtenti < ActiveRecord::Base
  self.table_name = "another_name"
  alias_attribute :name, :name_of_thing
end

#2


0  

Yes you can pass table name in model like:

是的,您可以在模型中传递表名称,如:

class YourModel < ActiveRecord::Base
  self.table_name = "pass_table_name_here"
end