我是一個初學者,我正在學習Beginning Rails 4第三版: 我的rails的版本是4.2.4,Windows 8.1和Ruby是2.1.6。關於多對多協會:ID不保存到數據庫
我有3種型號的豐富許多-to-many關聯:
1-評論
2-第
3-用戶
class Comment < ActiveRecord::Base
belongs_to :article
end
class Article < ActiveRecord::Base
validates_presence_of :title
validates_presence_of :body
belongs_to :user
has_and_belongs_to_many :categories
has_many :comments
def long_title
"#{title} - #{published_at}"
end
end
class User < ActiveRecord::Base
has_one :profile
has_many :articles, -> {order('published_at DESC, title ASC')},
:dependent => :nullify
has_many :replies, :through => :articles, :source => :comments
end
我想這個問題問你是否當我嘗試通過這個關聯創建評論時,創建的評論有nil id,因此不保存到數據庫。
例如,我在軌道控制檯中嘗試了以下內容。
article.comments.create(name: 'Amumu', email: '[email protected]', body: 'Amumu is lonely')
而且我得到了以下結果。
#<Comment id: nil, article_id: 4, name: "Amumu", email: "[email protected]", body: "Amumu is lonely", created_at: nil, updated_at: nil>
爲什麼評論會有一個無ID?我希望它有一個自動生成的ID,所以保存到數據庫。
它可能未能保存。檢查結果,看看是否有任何錯誤 - 它會通過'@ comment.errors'訪問 – Swards