Rails: Creating models from existing tables?

前端 未结 1 1172
旧巷少年郎
旧巷少年郎 2020-12-09 12:31

I have tables already created from a different project. Their names are formatted like aaa_bbb_ccc_ffffd (all non plural and some parts aren\'t a convention word). I have succ

相关标签:
1条回答
  • 2020-12-09 13:04

    just a theory, not sure how this would work in real app:

    create models named as ActiveRecord convention requires, for example for table aaa_bbb_ccc_ffffd you'll create a model AaaBbb and map this model to your table:

    class AaaBbb < ActiveRecord::Base
        self.table_name = "aaa_bbb_ccc_ffffd"
    end
    

    or a more human example:

    class AdminUser < ActiveRecord::Base
        self.table_name = "my_wonderfull_admin_users"
    end
    

    Now you'll have AaaBbb as resource in routes meaning you'll have a url like:

     .../aaa_bbb/...
    

    and if you want to use the table name name in url I guess you could rewrite the route:

    get 'aaa_bbb_ccc_ffffd/:id', "aaa_bbb#show", as: "aaa_bbb"

    again, just a theory that might help you out. I haven't worked with such cases yet but would've start from this.


    edit

    to automate model creation from database:

    https://github.com/bosko/rmre

    but I think this will create models by rails convention with wierd names that you'll have to use as resource in your app.


    A good template that I found on SO in case you want to use a model name different from table name:

    class YourIdealModelName < ActiveRecord::Base
      self.table_name = 'actual_table_name'
      self.primary_key = 'ID'
    
      belongs_to :other_ideal_model, 
        :foreign_key => 'foreign_key_on_other_table'
    
      has_many :some_other_ideal_models, 
        :foreign_key => 'foreign_key_on_this_table', 
        :primary_key => 'primary_key_on_other_table'
    end
    
    0 讨论(0)
提交回复
热议问题