I have an app that has 3 specific models; User, Country and City. The ideal relationship for each would be as follow:
User
- has_many :countries
- has_many :cities, through: :country
Country
- has_many :users
- has_many :cities
City
- has_many :users
- belongs_to :country
Most of those relationships are fairly straight forward, however, the User-to-City relationship is giving me a bit of a problem. I want to be able to assign a city to a user, as long as the user has been assigned to the country associated to the city. Right now I am not even able to assign a user a city, let alone institute the correct logic for the restriction.
So far what I have been able to read and search has led to the below. Please let me know if you need anything else. Any help is much appreciated!
User.rb
class User < ApplicationRecord
before_save { self.email = email.downcase}
#attr_accessible :username, :email
validates_confirmation_of :password
has_secure_password
validates :username, presence: true, length: { maximum: 25 }, uniqueness: {case_sensitive: false}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }
validates :password, presence: true, confirmation: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
has_many :trips
has_many :visits, through: :trips
has_many :countries, through: :trips
has_many :cities, through: :visits
end
Country.rb
class Country < ApplicationRecord
has_many :trips
has_many :cities
has_many :users, through: :trips
end
City.rb
class City < ApplicationRecord
has_many :visits
has_many :users, through: :visits
belongs_to :country
end
Trip.rb
class Trip < ApplicationRecord
belongs_to :country
belongs_to :user
has_many :visits
has_many :cities, through: :visits
end
Visit.rb
class Visit < ApplicationRecord
belongs_to :trip
belongs_to :city
has_one :country, through: :city
has_one :user, through: :trip
end
Aucun commentaire:
Enregistrer un commentaire