mardi 18 octobre 2016

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?

Aucun commentaire:

Enregistrer un commentaire