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.
2 Answers
The table name can be specified using table_name class method.
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:
class CreateUtenti < ActiveRecord::Base
self.table_name = "another_name"
alias_attribute :name, :name_of_thing
end
3 Comments
Giovanni Di Clemente
Thanks to you too. In this case rake db:migrate give me this error: rake aborted! NoMethodError: undefined method `table_name=' for CreateUtenti:Class
Igor Drozdov
@GiovanniDiClemente does your CreateUtenti class inherits from ActiveRecord::Base?
Igor Drozdov
what Rails version do you use?
Yes you can pass table name in model like:
class YourModel < ActiveRecord::Base
self.table_name = "pass_table_name_here"
end
2 Comments
Giovanni Di Clemente
Thank for your answer. I have tried but rake db:migrate give me an error: rake aborted! ArgumentError: wrong number of arguments (given 2, expected 0..1)
Giovanni Di Clemente
Caused by: ArgumentError: wrong number of arguments (given 2, expected 0..1) Tasks: TOP => db:migrate (See full trace by running task with --trace) Macintosh:telwebtt giovannidiclemente$ rake db:migrate --trace ** Invoke db:migrate (first_time) ** Invoke db:load_config (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:load_config ** Execute db:migrate rake aborted! ArgumentError: wrong number of arguments (given 2, expected 0..1)