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」,但我不認爲這是我的問題。
也許複製和粘貼失敗,但是這是一個語法錯誤:'has_many:tags,:through:taggings'。它可以是':through =>:taggings'或'through::taggings'。 – Robin 2015-02-24 17:38:57
沒有運氣,對不起:)。雖然你的建議將有助於未來的項目!我喜歡使用這種火箭。 – itiswicked 2015-02-24 17:47:25
出於好奇,這項工作: 'a = Article.first' 'a.tags << Tag.new(name:「cool」)' – tagCincy 2015-02-24 18:47:43