gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:13:57 30 4
gpt4 key购买 nike

我是 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com