Search code examples
ruby-on-railsrubymodel-view-controllermodels

Ruby on Rails Data Table Setup


I am currently trying to create an app that tracks a users travel. Ideally I would like a user to be able to select countries that they have visited, and then be able to select cities that they my have visited in the countries that they have selected.

In my initial setup while testing the scenario I was able to set up a many-to-many relationship between a User model and Country model through a Trip model. My confusion comes when I try to add in the City model and set it up. I know it would have a one-to-many relationship with Country model (Example belongs_to :country), and a many-to-many with the users model. What I don't want though is a user to be able to assign a city without assigning the country first. It seems simple, and I assume I have to do some sort of validation to get this scenario to work, however I cannot find an exact answer to my needs.

Any help would be much appreciated.


Solution

  • this is just an idea about your case, how about if you setup many to many between users and cities through trip model, and then you setup one to many between country to cities.

    class User < ActiveRecord::Base
      # -> trips -> cities
      has_many :trips, :dependent => :destroy
      accepts_nested_attributes_for :trips,   :allow_destroy => :true  
      has_many :cities, through: :trips
    end
    
    class Trip < ActiveRecord::Base
      belongs_to :User
      belongs_to :City
    end
    
    class City < ActiveRecord::Base
      # -> trips -> users
      has_many :trips, :dependent => :destroy
      accepts_nested_attributes_for :trips,   :allow_destroy => :true  
      has_many :users, through: :trips
      # ->  
      belongs_to :Country
    end
    
    class Country < ActiveRecord::Base
      # -> cities
      has_many :cities, :dependent => :destroy
      accepts_nested_attributes_for :cities,   :allow_destroy => :true  
    end