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

Ruby on rails 关于多对多关联:id未保存到数据库,ruby-on-rails,many-to-many,associations,Ruby On Rails,Many To Many,Associations,我是rails的初学者,正在学习入门rails 4第3版: 我的rails版本是4.2.4,Windows8.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_pres

我是rails的初学者,正在学习入门rails 4第3版: 我的rails版本是4.2.4,Windows8.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
我得到了以下结果

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

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

尝试使用
create而不是
创建
-它将显示所有错误

此外,我认为您应该在文章模型中为:评论添加
accepts\u nested\u attributes\u,并在用户模型中为:文章添加
accepts\u nested\u attributes\u

编辑:


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

在考虑了我在这里得到的一些评论后,我开始了解我的错误

实际上,我的评论模型如下

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
class注释

是的,我忘了在注释模型中放了一个validate方法。由于此验证方法,任何在“published_at”属性中没有值的注释都不会保存

它可能无法保存。检查结果以查看是否有任何错误-可通过
@comment访问。错误
我了解了使用create时发生此问题的原因!而不是“创建”。我只是忘了在注释模型中放了一个validate方法。谢谢你的评论。
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