Josué Almonasi Josué Almonasi - 1 month ago 11
Ruby Question

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

I'm working with three tables as follows:

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


and comentario.rb

class Comentario < ActiveRecord::Base
belongs_to :article
end


Everything works fine until I attempt to add a 'comentario' and returns this error

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


This is the code I use to create a new '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


The output returns an error in the line where I create
@comentario
from calling
@article
but I can't see why since Ruby documentation says that once I associate
comentario
to
article
using
:through
, I can simply call something like
@article.comentario
.

Any idea of what is causing this error?
or do you have any suggestion on how to achieve this association in any other way?

Answer

Ok. The issue is that Rails is confused about which article to use here.

Your Comment model belongs_to :article but also your Commentario belongs_to :article... so if you use @article.commentarios - it's confused as to whether the article refers to the article of the comment or the article of the commentario.

You will probably need to update your form to be more explicit about what you're referring to. A form for the commentario should actually include fields for the comment it creates.

Somebody else had the same problem here. You may wish to look at the solution here: "Cannot modify association because the source reflection class is associated via :has_many"