【发布时间】:2016-08-09 23:48:03
【问题描述】:
大家好,我刚刚遇到了这个问题,我正在关注教程,我试图在我的文章和类别之间创建多对多关联,所以我通过键入添加了 article_category 模型:
rails g model article_category article_id:integer category_id:integer
在这个模型里面我输入了
belongs_to :article
belongs_to :category
inside article.rb:
has_many :article_categories
has_many :categories, through: :article_categories
在 category.rb 中:
has_many :article_categories
has_many :articles, through: :article_categories
所以我去了控制台:通过键入以下内容进行关联:
Article.all
Article.first
我检查了 article.categories
#<ActiveRecord::Associations::CollectionProxy []>
我也尝试过分类
category.all
category.first
结果是:
category
=> #<Category id: 6, name: "sport", created_at: "2016-04-11 06:41:25", updated_at: "2016-04-11 06:41:25">
article
=> #<Article id: 25, title: "kkkk", description: "lll", created_at: "2016-04-13 07:32:38", updated_at: "2016-04-13 07:32:38", user_id: 21>
所以我尝试通过键入以下内容使这篇文章成为该类别的一部分:
category.articles << article
所以我得到了这个错误:
INSERT INTO `article_categories` (`article_id`, `category_id`, `created_at`, `updated_at`) VALUES (25, 6, '2016-04-18 09:06:58', '2016-04-18 09:06:58')
(12.9ms) ROLLBACK
NoMethodError: undefined method `name' for nil:NilClass
this is the error 任何想法的家伙 谢谢
【问题讨论】:
-
你能把这个结果过去吗:
category.errors.full_messages? -
它只是给我空的哈希 []
-
这很奇怪!您是否尝试过检查:
article.categories << category?尝试并发布结果... -
@AdelAlmaleh 你有类似
before_save之类的回调吗? -
@usmanali 不,但我只是上传我的控制器,你可以检查一下
标签: ruby-on-rails ruby associations