无法修改关联“:has_many”。在 rails 上使用 Ruby

Cannot modify association ":has_many." using Ruby on rails

我正在使用如下三个表:

article.rb

class Article < ActiveRecord::Base
  has_many :comments
  has_many :comentarios, :through => :comments
end

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :article
  has_many :comentarios 
end

和comentario.rb

class Comentario < ActiveRecord::Base
  belongs_to :article
end

一切正常,直到我尝试添加 'comentario' 和 returns 这个错误

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection in ComentariosController#create 
Cannot modify association 'Article#comentarios' because the source reflection class 'Comentario' is associated to 'Comment' via :has_many.

这是我用来创建新 'comentario'

的代码

comentarios_controller.rb

class ComentariosController < ApplicationController

  def new
      @comentario = Comentario.new
  end

  def create
   @article = Article.find(params[:article_id])
   @comentario = @article.comentarios.create(comentario_params)
   redirect_to article_path(@article)
 end

 private
   def comentario_params
     params.require(:comentario).permit(:comentador, :comentario)
   end
end

输出 returns 在我通过调用 @article 创建 @comentario 的行中出现错误,但我不明白为什么,因为 Ruby 文档说一旦我使用 :throughcomentario 关联到 article,我可以简单地调用 @article.comentario.

知道是什么导致了这个错误吗? 或者你对如何以任何其他方式实现这种关联有什么建议吗?

好的。问题是 Rails 对在此处使用哪篇文章感到困惑。

你的 Comment 模型 belongs_to :article 还有你的 Commentario belongs_to :article...所以如果你使用 @article.commentarios - 很困惑文章是否引用评论的文章或评论的文章。

您可能需要更新表单以更明确地说明您所指的内容。 commentario 的表单实际上应该包括它创建的评论的字段。

其他人在这里遇到了同样的问题。您不妨在这里查看解决方案: