关联many_many NoMethodError:nil的未定义方法`name':NilClass

时间:2016-04-18 09:51:11

标签: ruby-on-rails ruby associations

大家好我刚刚遇到这个问题我正在关注教程,我试图创建我的文章和类别之间的多对多关联,所以我通过输入添加了article_category模型:

rails g model article_category article_id:integer category_id:integer

在我输入的这个模型里面

belongs_to :article
belongs_to :category

在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 

ad我检查了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 controller

application controller

category controller

2 个答案:

答案 0 :(得分:0)

尝试在您的加入模型&#39; s(article_category)迁移中添加索引。

add_index :article_categories, :article_id
add_index :article_categories, :category_id

如果不让我知道,那应该可以解决问题。

答案 1 :(得分:0)

你可以试试category.article_ids << article_ids吗?

对于许多人来说,我认为rails允许你使用_ids来保存id而不是你想要的整个对象。

然后您可以访问category.articles并检查文章是否确实已添加