我在我的程序中有3个主要模型;用户,国家,城市。在Rails中创建模型关系的问题
用户和乡村有许多一对多的关系,我与 跳闸模式加入。
用户和城市有多对多的关系,我加入了 访问模式。
国家和城市有一对多的关系。
当我运行rails db:migrate
我没有得到任何错误,当我尝试和种子数据或进入控制台创建一个城市也不会保存所有出现很好,但是。任何用户或国家都将成功创建,并且我可以在它们之间建立关系。
查看我的模特儿。
user.rb
class User < ApplicationRecord
before_save { self.email = email.downcase }
#attr_accessible :user_name, :email
validates_confirmation_of :password
has_secure_password
validates :user_name, presence: true, length: { maximum: 25 }
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][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
has_many :countries, through: :trips
has_many :cities, through: :visits
end
city.rb
class City < ApplicationRecord
has_many :visits
has_many :users, through: :visits
belongs_to :country
end
country.rb
class Country < ApplicationRecord
has_many :trips
has_many :cities
has_many :users, through: :trips
end
trip.rb
class Trip < ApplicationRecord
belongs_to :country
belongs_to :user
end
visit.rb
class Visit < ApplicationRecord
belongs_to :city
belongs_to :user
end
我本来甚至没有访问模型,我只是过跳闸模型都加入许多一对多的关系。但是,在试图解决这个问题时,我将它分开了。
任何有关这个问题的帮助,将不胜感激。如果您需要更多信息,请告诉我。
你确定你有所有模型的迁移? db:如果无事可做,迁移将成功返回。当你试图保存时,你会得到什么样的信息? (尝试使用保存!而不是从控制台保存,如果它只是返回false)。 – cpm
我得到'ActiveRecord :: RecordInvalid:验证失败:国家必须存在',当一个保存!我有国家,我尝试了一些像'Country.find(1).cities << [City.create(name:“Toronto”)]'',希望在创建该城市时将该城市分配给该国家将有所帮助,但不会运气。 –
你用country_id保存城市吗? – hashrocket