关于多对多关联:id未保存到数据库

时间:2015-11-03 03:23:54

标签: ruby-on-rails many-to-many associations

我是rails的初学者,我正在学习Beginning Rails 4 3rd Edition: 我的导轨'版本是4.2.4,Windows 8.1,Ruby是2.1.6。

我有3个丰富的多对多协会模型:

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,因此不会保存到数据库中。

例如,我在rails控制台中尝试了以下内容。

article.comments.create(name: 'Amumu', email: 'amu@daum.net', body: 'Amumu is lonely')

我得到了以下结果。

#<Comment id: nil, article_id: 4, name: "Amumu", email: "amu@daum.net", body: "Amumu is lonely", created_at: nil, updated_at: nil>

为什么评论会出现nil id?我希望它有一个自动生成的id,因此保存到数据库中。

2 个答案:

答案 0 :(得分:1)

尝试使用create!代替create - 它会显示所有错误。

另外,我认为您应该在文章模型中添加accepts_nested_attributes_for :comments,在用户模型中添加accepts_nested_attributes_for :articles

编辑:

请在评论和文章控制器以及新评论和新文章表单中显示您的代码。

答案 1 :(得分: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

是的,我忘记了我在Comment模型中放了一个验证方法。由于这种验证方法,任何没有值的评论都在&lt; published_at&#39;属性未保存。