我在我的程序中有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