ruby-on-rails - 关于多对多关联 : id is not saving to database

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

我是 Rails 的初学者,正在学习 Beginning Rails 4 第 3 版: 我的 Rails 版本是 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

我想问你的问题是,当我尝试通过这个关联创建评论时,创建的评论的 ID 为 nil,因此没有保存到数据库中。

例如,我在 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>

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

最佳答案

尝试使用 create! 而不是 create - 它会显示所有错误。

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

编辑:

请显示您来自评论和文章 Controller 以及新评论和新文章表单的代码。

关于ruby-on-rails - 关于多对多关联 : id is not saving to database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33490850/

相关文章:

ruby-on-rails - 什么时候调用 rails 中的 after_touch 回调

ruby-on-rails - rails : validate uniqueness of two columns (together)

ruby-on-rails - rails partials 中的收集计数器

ruby-on-rails - 如何使用 if 语句包装代码块,这意味着有没有 ruby​​ 方法可以做到这一点?

python - 在 SQLAlchemy 中更新关联对象中的字段

database - Django 与附加字段的多对多关系

mysql - Laravel Eloquent 多对多关系的问题

ruby-on-rails - 外键 (class_id) 未填充在 belongs_to 关联中

ruby-on-rails - rails : How to render path to namespaced file

symfony - Doctrine 不会在我的 OneToMany 关联中保存数据