ruby-on-railsrubydatabaseoptimizationproject-planning

Ruby on Rails - need an idea


I need an advice or maybe better to call it idea. :)

Imagine you have an class, lets call it Tree. Trees are in different countries but for some of them there are native and for some there are not. I need the best way how to connect Tree with Country so for each country same Instance will have different values. Like for example pine will have native set as true for Canada, but not for Egypt, etc.

I know that I can have multiple records, but I'd rather prefer some smooth and pretty solution with avoidance of creating thousands of records for one Instance.

For now I need just an ideas.


Solution

  • I would model it like this:

    class Tree
      has_many :tree_locations
      has_many :countries, through: :tree_locations
      has_many :native_tree_locations, class_name: 'TreeLocation', 
                                  -> { where(native: true) }
      has_many :native_countries, through: :native_tree_locations, 
                                  class_name: 'country'
    
    class TreeLocation
      belongs_to :tree
      belongs_to :country
      # and a `native` boolean flag in the DB
    
    class Country
      has_many :tree_locations
      has_many :trees, through: :tree_locations
      # ...
    

    This allows for a given tree: