itiswicked
itiswicked

Reputation: 1

Rails association in model error

I am using rails 4.2.0. and I am getting this error:

ActiveRecord::HasManyThroughAssociationNotFoundError: 
Could not find the association :taggings in model Article

Here are my models:

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :articles, :through => :taggings
end

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

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

Tagging is an intermediary model for the many-to-many relationship between Article and Tag.

And if it helps, my schema:

ActiveRecord::Schema.define(version: 20150224161732) do

  create_table "articles", force: :cascade do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "comments", force: :cascade do |t|
    t.string   "author_name"
    t.text     "body"
    t.integer  "article_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_index "comments", ["article_id"], name: "index_comments_on_article_id"

  create_table "taggings", force: :cascade do |t|
    t.integer  "tag_id"
    t.integer  "article_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "taggings", ["article_id"], name: "index_taggings_on_article_id"
  add_index "taggings", ["tag_id"], name: "index_taggings_on_tag_id"

  create_table "tags", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

I run this code in rails console to test my associations:

a = Article.first
a.tags.create name: "cool"

And I get the above error.

I have seen similar questions where the response "if you have through: :x, you have to have has_many :x first," but I don't think that is my issue.

Upvotes: 0

Views: 388

Answers (1)

Andrew Kim
Andrew Kim

Reputation: 3335

This might be a silly question, but have you tried creating a Tagging independent of the Article model? If you haven't, than it could be something messed up with the database not having the Tagging model. Otherwise, associations look fine and should work. The only other thing I can think of is incorrect file names for your models folder

Upvotes: 0

Related Questions