dynamic table names for Active Record models

后端 未结 7 1343
感情败类
感情败类 2021-01-27 13:25

I have an interesting Active Record problem and I\'m not quite sure what the cleanest solution is. The legacy database that I am integrating with has a strange wrinkle in its sc

7条回答
  •  有刺的猬
    2021-01-27 13:42

    Assumption 1: you know what type of car you're looking at, so you can tell if it's a ford or a dodge.

    Lets put the car make in an attribute called (of all things) make. You should normalize this later, but for now lets keep it simple.

    CREATE TABLE cars (
      `id` int(11) NOT NULL auto_increment,
      `name` varchar(255),
      'make' varchar(255),
      #ect
    )
    
    
    class Wheel < ActiveRecord::Base
       def find_by_make(iMake)
           select("wheels_for_#{iMake}.*").from("wheels_for_#{iMake}");
       end
     #...
    end
    

    You could add some protection in there to validate and downcase your iMake. You could also do something to ensure your table exists.

    Now writing to the table.. I'm not sure how that would work. I've only ever read from it. Perhaps its something simple too.

提交回复
热议问题