【问题标题】:Associations many_many NoMethodError: undefined method `name' for nil:NilClass关联 many_many NoMethodError: nil:NilClass 的未定义方法“名称”
【发布时间】: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 &lt;&lt; category?尝试并发布结果...
  • @AdelAlmaleh 你有类似before_save 之类的回调吗?
  • @usmanali 不,但我只是上传我的控制器,你可以检查一下

标签: ruby-on-rails ruby associations


【解决方案1】:

尝试在连接模型的 (article_category) 迁移中添加索引。

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

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

【讨论】:

    【解决方案2】:

    你能试试category.article_ids &lt;&lt; article_ids吗?

    对于很多很多,我认为 rails 使您能够使用 _ids 来保存 id 而不是您想要的整个对象。

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

    【讨论】:

    • main:Object 的未定义局部变量或方法 `article_ids'
    • 您能在这里评论category.articles 的示例输出吗?谢谢。您可以查看此链接api.rubyonrails.org/classes/ActiveRecord/Associations/… 并查看“has_many”部分,即示例部分。它说它添加了_ids helper。
    • 如果一切都失败了,请尝试重新启动您的 Rails 服务器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2013-01-14
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多