Prem
Prem

Reputation: 3543

Rails 'DB - no such column' error for has_many through relationship

I created a has_many :through relationship for a rails app I am creating. However, I am unable have nested attributes for the many to many relationship.

My models are as follows:

article.rb

class Article < ActiveRecord::Base
  attr_accessible :body, :title
  has_many :article_tags
  has_many :tags, :through => :article_tags, :foreign_key => :tag_id    
  accepts_nested_attributes_for :tags, reject_if: :all_blank    
  attr_accessible :tags_attributes    
  validates_presence_of [:body, :title]
end

tag.rb:

class Tag < ActiveRecord::Base
   has_many :article_tags
   has_many :articles, :through => :article_tags, :foreign_key => :article_id
   attr_accessible :name
   validates_presence_of :name

   accepts_nested_attributes_for :articles, reject_if: :all_blank

   attr_accessible :articles_attributes
end

article_tag.rb:

class ArticleTag < ActiveRecord::Base
 belongs_to :article
 belongs_to :tag
end

Now in my view for the article (show.html.slim), I want to show all tags that belong to the article using the line:

- @article.tags.each do |t|
  = t.name

However, I get the error: SQLite3::SQLException: no such column: article_tags.article_id: SELECT "tags".* FROM "tags" INNER JOIN "article_tags" ON "tags"."id" = "article_tags"."tag_id" WHERE "article_tags"."article_id" = 1

This problem is solved.

For anybody who needs to know:

You must manually add the foreign keys in the migration and the schema. I added them and voila! it works!

Thanks to Dan Reedy for his help!

Upvotes: 0

Views: 525

Answers (2)

You must use has_and_belongs_to_many in this situation.

Upvotes: 1

Dan Reedy
Dan Reedy

Reputation: 1857

Your ArticleTag class is incorrect. The belongs_to associations should be singular.

class ArticleTag < ActiveRecord::Base
  belongs_to :article
  belongs_to :tag
end

Upvotes: 2

Related Questions