2015-02-24 80 views
0

我正在使用rails 4.2.0。和我收到此錯誤:模型錯誤中的滑軌關聯

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

這裏是我的模型:

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 

標記是條和標籤之間的許多一對多關係的中介模式。

如果有幫助,我的架構:

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 

我在鐵軌控制檯運行這段代碼來測試我的協會:

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

我得到上述錯誤。

我已經看到類似的問題,如果您的答案是「如果您已經通過了::x,您必須首先有has_many:x」,但我不認爲這是我的問題。

+0

也許複製和粘貼失敗,但是這是一個語法錯誤:'has_many:tags,:through:taggings'。它可以是':through =>:taggings'或'through::taggings'。 – Robin 2015-02-24 17:38:57

+0

沒有運氣,對不起:)。雖然你的建議將有助於未來的項目!我喜歡使用這種火箭。 – itiswicked 2015-02-24 17:47:25

+0

出於好奇,這項工作: 'a = Article.first' 'a.tags << Tag.new(name:「cool」)' – tagCincy 2015-02-24 18:47:43

回答

0

這可能是一個愚蠢的問題,但您是否嘗試過創建一個獨立於Article模型的標籤?如果你還沒有,比它可能是一個混亂的數據庫沒有標籤模型。否則,協會看起來很好,應該工作。我唯一能想到的其他事情是模型文件夾的文件名不正確