2015-11-03 59 views
3

我是一個初學者,我正在學習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,所以保存到數據庫。

+2

它可能未能保存。檢查結果,看看是否有任何錯誤 - 它會通過'@ comment.errors'訪問 – Swards

回答

1

考慮到我在這裏得到的一些評論後,我看到了我的錯誤。

其實我的評論模型如下。

class Comment < ActiveRecord::Base 
    belongs_to :article 

    validates_presence_of :name, :email, :body 
    validate :article_should_be_published 

    def article_should_be_published 
    errors.add(:article_id, "isn't published yet") if article && !article.published? 
    end 
end 

是的,我忘了我已經在評論模型中加入了一個驗證方法。由於此驗證方法,不會保存'published_at'屬性中沒有值的任何評論。

1

嘗試使用create!而不是create - 它會告訴你所有的錯誤。

此外,我認爲你應該在用戶模型中添加文章模型accepts_nested_attributes_for :commentsaccepts_nested_attributes_for :articles

編輯:

請出示從評論和文章控制器,以及新評論,新文章的形式你的代碼。

+0

我明白了爲什麼這個問題發生時,我用創建!而不是「創造」。我只是忘記了我已經在評論模型中加入了一個驗證方法。感謝您的評論。 –

+0

不客氣:) – weezing